Validating a TextBox Using an Error Provider in Visual Basic 2008

Today, I will teach you how to validate a Textbox using an ErrorProvider in Visual Basic 2008. With this, you will know what are the inputs you are going to put in the textbox and it will notify you whatever errors that you might encounter. Let’s begin: Open Visual Basic 2008 and create a new windows application. Drag the two TextBoxes, a Button and an Error Provider in the Form. And it will look like this. First Form After that, double click the Button to fire the click event handler and do the following code to the method.
  1.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  2.  
  3.         'CHECKING IF THE TWO TEXTBOXES ARE CLEARED
  4.         If txtstring.Text = "" And txtnumber.Text = "" Then
  5.             ErrorProvider1.SetError(txtstring, "Field must be filled up.")
  6.             ErrorProvider1.SetError(txtnumber, "Field must be filled up.")
  7.         Else
  8.             'THE ERROR PROVIDER WILL BE CLEARED.
  9.             ErrorProvider1.SetError(txtstring, "")
  10.             ErrorProvider1.SetError(txtnumber, "")
  11.  
  12.             'CONDITION FOR THE STRING VALUE
  13.             'CHECK IF THE INPUT IS A NUMERIC VALUE THEN PERFORM THE ERROR PROVIDER
  14.             'IF NOT, CLEAR THE ERROR PROVIDER.
  15.             If IsNumeric(txtstring.Text) Then
  16.                 'THE ERROR PROVIDER WILL APPEAR AND WILL NOTIFY THE PROBLEM TO THE USER.
  17.                 ErrorProvider1.SetError(txtstring, "Input string value is not valid.")
  18.             Else
  19.                 'THE ERROR PROVIDER WILL BE CLEARED.
  20.                 ErrorProvider1.SetError(txtstring, "")
  21.             End If
  22.  
  23.             'CONDITION FOR THE NUMERIC VALUE
  24.             'CHECK IF THE INPUT IS NOT A NUMERIC VALUE THEN PERFORM THE ERROR PROVIDER
  25.             'IF NUMERIC, CLEAR THE ERROR PROVIDER.
  26.             If Not IsNumeric(txtnumber.Text) Then
  27.                  'THE ERROR PROVIDER WILL APPEAR AND WILL NOTIFY THE PROBLEM TO THE USER.
  28.                 ErrorProvider1.SetError(txtnumber, "Input numeric value is not valid.")
  29.             Else
  30.                 'THE ERROR PROVIDER WILL BE CLEARED.
  31.                 ErrorProvider1.SetError(txtnumber, "")
  32.             End If
  33.  
  34.         End If
  35.  
  36.     End Sub
Run your project and click the Button to perform the code in the method. Output: Output

Add new comment