在一个处理程序中处理所有文本框事件

con*_*dor 3 vb.net

我知道如何处理表单中的文本框事件.但是想让这段代码更短,因为我会有30个文本框.使用它是低效的:

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
Run Code Online (Sandbox Code Playgroud)

有没有办法缩短处理程序?

Tim*_*ter 9

您可以使用Controls.OfType+ AddHandler编程.例如:

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

一个处理程序为所有:

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
Run Code Online (Sandbox Code Playgroud)

  • 我认为,这里没有必要使用select语句,而是我们可以写一行像这样的`MsgBox(DirectCast(sender,TextBox).Text)`:) (2认同)
  • @GLOIERTECH.:我刚刚复制了OP的代码,我认为这只是示例代码,他实际上想要以不同的方式处理这些情况.我想表明可以识别原始的`TextBox`(尽管OP已经意识到了它). (2认同)