vb.net – 在一个处理程序中处理所有文本框事件

前端之家收集整理的这篇文章主要介绍了vb.net – 在一个处理程序中处理所有文本框事件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我知道如何处理表单中的文本框事件.但是想让这段代码更短,因为我会使用30个文本框.使用它是低效的:
  1. 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
  2. Dim tb As TextBox = CType(sender,TextBox)
  3.  
  4. Select Case tb.Name
  5. Case "TextBox1"
  6. MsgBox(tb.Text)
  7. Case "TextBox2"
  8. MsgBox(tb.Text)
  9. End Select
  10. End Sub

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

您可以通过编程方式使用 Controls.OfType AddHandler.例如:
  1. Dim textBoxes = Me.Controls.OfType(Of TextBox)()
  2. For Each txt In textBoxes
  3. AddHandler txt.TextChanged,AddressOf txtTextChanged
  4. Next

一个处理程序为所有:

  1. Private Sub txtTextChanged(sender As Object,e As EventArgs)
  2. Dim txt = DirectCast(sender,TextBox)
  3. Select Case txt.Name
  4. Case "TextBox1"
  5. MsgBox(txt.Text)
  6. Case "TextBox2"
  7. MsgBox(txt.Text)
  8. End Select
  9. End Sub

猜你在找的VB相关文章