Handling all textbox event in one Handler

后端 未结 4 1920
感动是毒
感动是毒 2020-12-18 11:27

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         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-18 11:59

    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
    

提交回复
热议问题