Results 1 to 2 of 2

Thread: Validating User Input

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Dec 2006
    Location
    Georgia
    Posts
    170

    Validating User Input

    This may seem like a silly question, but how do I verify that the data a user enters is the right type of data. That is, I need a number to do math with, I can't allow the user to enter text. How do I check this at runtime?

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Validating User Input

    This is a very oft-asked question, so a forum search would yield plenty of information.

    The easiest way is to use a NumericUpDown control. If that's not suitable then you can use the TryParse of the appropriate numeric type, e.g.
    VB Code:
    1. Dim number As Integer
    2.  
    3. If Integer.TryParse(myTextBox.Text, number) Then
    4.     'The "number" variable contains the numeric value.
    5. Else
    6.     'The TextBox does not contain a valid number.
    7. End If
    If the NUD is not suitable for whatever reason then the most professional way is to inherit the TextBox and prevent the user entering invalid characters at all. There are numerous examples of doing this by handling the KeyPress event already posted so I won't add to their number. Note though, that to do a full and proper job there is more to consider than just that.

    Finally, the WFC link in my signature includes a NumberBox control that does what I just mentioned. It is the most complete implementation that I've seen that doesn't cost money.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width