Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

vb.net - Handling all textbox event in one Handler

I do know how to handle event of textboxes in my form. But want to make this code shorter because I will 30 textboxes. It's inefficient to use this:

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged, TextBox2.TextChanged, TextBox3.TextChanged, TextBox4.TextChanged, TextBox5.TextChanged, TextBox6.TextChanged, TextBox7.TextChanged, TextBox8.TextChanged, TextBox9.TextChanged, TextBox10.TextChanged
    Dim tb As TextBox = CType(sender, TextBox)

    Select Case tb.Name
        Case "TextBox1"
            MsgBox(tb.Text)
        Case "TextBox2"
            MsgBox(tb.Text)
    End Select
End Sub

Is there a way to shorten the handler?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use Controls.OfType + AddHandler programmatically. For example:

Dim textBoxes = Me.Controls.OfType(Of TextBox)()
For Each txt In textBoxes
    AddHandler txt.TextChanged, AddressOf txtTextChanged
Next

one handler for all:

Private Sub txtTextChanged(sender As Object, e As EventArgs)
    Dim txt = DirectCast(sender, TextBox)
    Select Case txt.Name
        Case "TextBox1"
            MsgBox(txt.Text)
        Case "TextBox2"
            MsgBox(txt.Text)
    End Select
End Sub

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...