目前,我在Form.vb上有这个:
Private Sub txtBox1_Leave(sender As Control, e As EventArgs) Handles txtBox1.Leave
'Some code
End Sub
...
Private Sub txtBox10_Leave(sender As Control, e As EventArgs) Handles txtBox10.Leave
'Some code
End Sub
困扰我的是:所有这些事件都在做同样的事情。是否有可能以编程方式获得相关控件的列表并迭代它们,添加此类事件?这将允许我减少应用程序/编码工作中的代码量。类似的东西:
For Each c As Control in listOfControls
'Add event for c here which calls method
Next
我真的认为有一种简单的方法可以做到这一点,但到目前为止我尝试过的所有内容(例如AddHandler)都不起作用。有什么想法吗?
谢谢
答案 0 :(得分:1)
是的,这很简单,可以创建一个方法,将所请求的事件添加到Control
,在表单加载之前将一组控件传递给该方法:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' add events to all requested controls
AddEvent(New Control() {TextBox1, TextBox2, TextBox3, Button1})
End Sub
Public Sub AddEvent(ByVal myControls() As Control)
For Each c As Control In myControls
AddHandler c.Leave, AddressOf Control_Leave
Next
End Sub
Private Sub Control_Leave(sender As Object, e As EventArgs)
MsgBox("Control is not in focus")
End Sub
End Class