Limit A TextBox To Less Than 20 Characters

Damosull

New member
Joined
Oct 21, 2013
Messages
1
Programming Experience
Beginner
Hi, I'm new to VB and doing my first college project.
For the project, we have to code a "name textbox", we have to code it so that if the user types in 20 characters or more, a message box appears with "error" or whatever. Thanks in advance for any advice I get.
 

IanRyder

Well-known member
Joined
Sep 9, 2012
Messages
1,130
Location
Healing, NE Lincs, UK
Programming Experience
10+
Hi,

Typically, if you wanted to limit the number of characters within a TextBox then you would just set the MaxLength Property of the TextBox to what you need.

If this is a college exercise, then you would need to code the KeyPress Event of the TextBox and test the value of e.KeyChar (being the Char Value of the key that was pressed) with the Char Structure to see if this character is NOT a Control character:-

Char Structure (System)

If the key pressed was not a Control character then you would need to test the Length of the current string in the TextBox and then either Handle the cancellation of the character that was pressed and show an error message or allow the character to be entered into the TextBox.

Hope that helps.

Cheers,

Ian
 
Top Bottom