Question ErrorProvider

JDS

Member
Joined
Mar 12, 2006
Messages
7
Programming Experience
1-3
Hi,

I am trying the ErrorProvider and want a text box to accept only numbers, 1 - 500. I want the ErrorProvider to appear if text is entered instead of a number. Is that possible and how would that be coded?

And is possible to not display the ErrorProvider's exclamation point if no error or omission is made by the user?

Thank you,

JDS
 
Assuming you mean only integer, I'd suggest using a NumericUpDown instead of a TextBox.

If you want to stick with the TextBox though, this is how your ErrorProvider would work:
VB.NET:
Private Sub TextBox1_TextChanged(ByVal sender As Object, _
                                 ByVal e As EventArgs) Handles TextBox1.TextChanged
    Dim value As Integer

    If Integer.TryParse(Me.TextBox1.Text, value) AndAlso _
       value >= 1 AndAlso _
       value <= 500 Then
        Me.ErrorProvider1.SetError(Me.TextBox1, Nothing)
    Else
        Me.ErrorProvider1.SetError(Me.TextBox1, _
                                   "Please enter an integer from 1 to 500.")
    End If
End Sub
The only problem there is that the error will not be displayed initially if the TextBox is empty. For that you would set the "Error on ErrorProvider1" property of the TextBox in the designer. If you're setting the initial Text value of the TextBox then there's no need for that because that will trigger a TextChanged event and that will display the error if required.
 
Mr. McIlhinney,

G'day, Happy New Year, and thank you very much. I've decided to use the text box rather than the numericUpDown - better suited to my purposes. I have made some modifications to your code and all works wonderfully.

Again, thank you.

John Shellenberger (JDS)
 
Back
Top