我有一个方法,该方法将ComboBox作为参数,然后向其添加数据。添加数据时,将触发 SelectedIndexChangedEvent。有没有办法,在调用的方法中,我可以删除作为参数传递的任何 ComboBox 的上述事件处理程序,然后在方法末尾添加?我知道如何删除和添加特定的处理程序,但无法弄清楚如何根据传递的 ComboBox 进行操作。
这是方法..
Private Sub PopulateComboBox(ByRef cboBox As ComboBox, ByVal itemSource As String)
'Remove handler for cboBox
'Do stuff that would otherwise cause the event handler to execute
'Add handler for cboBox
End Sub
我有 4 个组合框 - 删除所有 4 个事件处理程序然后在代码末尾再次添加它们会更容易吗?但是,我想知道这是否可行,以便将来可以应用于可重用的代码
执行此操作的最基本方法是执行此操作:
Private Sub PopulateComboBox(ByRef cboBox As ComboBox, ByVal itemSource As String)
RemoveHandler cboBox.SelectedIndexChanged, AddressOf ComboBox1_SelectedIndexChanged
'Do stuff that would otherwise cause the event handler to execute
AddHandler cboBox.SelectedIndexChanged, AddressOf ComboBox1_SelectedIndexChanged
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
End Sub
另一种在某些情况下可能更好的选择是这样做:
Private _ignoreComboBox As ComboBox = Nothing
Private Sub PopulateComboBox(ByRef cboBox As ComboBox, ByVal itemSource As String)
_ignoreComboBox = cboBox
'Do stuff that would otherwise cause the event handler to execute
_ignoreComboBox = Nothing
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
If sender Is Not _ignoreComboBox Then
End If
End Sub
或者,要同时处理多个组合框:
Private _ignoreComboBoxes As List(Of ComboBox) = New List(Of ComboBox)()
Private Sub PopulateComboBox(ByRef cboBox As ComboBox, ByVal itemSource As String)
_ignoreComboBoxes.Add(cboBox)
'Do stuff that would otherwise cause the event handler to execute
_ignoreComboBoxes.Remove(cboBox)
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
If Not _ignoreComboBoxes.Contains(DirectCast(sender, ComboBox)) Then
End If
End Sub
这是一种方法:
' these happen to map to the same event handler
Private cb1Event As EventHandler = AddressOf cbx_SelectedIndexChanged
Private cb2Event As EventHandler = AddressOf cbx_SelectedIndexChanged
然后使用时:
PopulateComboBox(cb1, items, cb1Event)
PopulateComboBox(cb2, items, cb2Event)
' or
PopulateComboBox(cb3, items, AddressOf cbx_SelectedIndexChanged)
该方法将被声明为:
Private Sub PopulateComboBox(cboBox As ComboBox,
items As String, ev As EventHandler)
就个人而言,既然你知道所涉及的 cbo,我会在通话前这样做:
RemoveHandler cb1.SelectedIndexChanged, AddressOf cbx_SelectedIndexChanged
PopulateComboBox(cb1, items)
AddHandler cb1.SelectedIndexChanged, AddressOf cbx_SelectedIndexChanged
将所有信息传递给其他事情并没有太多收获,这样它就可以做你知道需要做的事情。