Validating textbox entries

When you retrieve a numeric value from a textbox, you may want to compare
it to some other preset value. For example, consider the following code:

Select Case Text1.Text
   Case 1 to 12
      MsgBox "Acceptable Value"
   Case Else
      MsgBox "Unacceptable Value"
End Select

You might think that this code would compare a numeric value in Text1 and
return Acceptable Value for values 1 through 12, and Unacceptable Value
for all other numbers. Instead, this code snippet displays the Acceptable
Value message for only 1, 10, 11, and 12, but not 2, 3, 4, etc. That's
because a textbox's Text property returns the value as a string, and so
compares them as such in the Select Case statement.

To avoid this unexpected glitch, convert the numbers with the Val()
function. This function automatically converts a string into the
appropriate type: integer, long, single, or double. The modified code
would look as follows:

Select Case Val(Text1.Text)
   Case 1 to 12
      MsgBox "Acceptable Value"
   Case Else
      MsgBox "Unacceptable Value"
End Select

You might also like...

Comments

ElementK Journals

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.” - Antoine de Saint Exupéry