user2823993
user2823993

Reputation:

is there a cleaner method of handling textbox validating events

I have 20+ textboxes on a form and I am wondering if there is a cleaner method that I can use to handle the validation of these controls other than using the intended validating event handlers.

What I have tried is looping through all of the controls on the form checking them for their proper valid values and displaying the ErrorProvider on the proper control if the value is not valid thus cutting down the 20+ event handlers into 30 lines of code. this process is in a function that will return either true or false that is called on a button click and will proceed with more logic if returns true.

I am wondering if this is improper or if I should just stick to the validating event handlers

Upvotes: 1

Views: 561

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125332

When you are using the same validation rule for all (or most of) your text boxes (as stated in comments) you can assign a single handler to Validating event of those text boxes and validate them in that handler. For example:

Private Sub TXT_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) _
    Handles TextBox1.Validating, TextBox2.Validating, TextBox3.Validating

    'Find the validating control
    Dim txt As TextBox = DirectCast(sender, TextBox)

    'Check validation for that control
    If (txt.Text.Length > 10) Then

        'Set validation message if the state is invalid
        Me.ErrorProvider1.SetError(txt, "Maximum length of text is 10 characters.")

        'Say the state is invalid
        e.Cancel = True
    Else

        'Clear probable privious validation error for that textbox
        Me.ErrorProvider1.SetError(txt, String.Empty)
    End If
End Sub

Upvotes: 0

Related Questions