删除和添加ComboBox作为参数传递的不同ComboBox的事件处理程序

时间:2016-01-16 18:23:50

标签: vb.net event-handling

我有一个方法,它将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个ComboBoxes - 它是否更容易删除所有4个事件处理程序,然后在代码的末尾再次添加它们?但是,我想知道这是否可行,以便我可以在将来申请可重复使用的代码

2 个答案:

答案 0 :(得分:1)

这是一种方式:

' 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

通过将所有信息传递给其他事物来获取其他东西并没有多少收获,因此它可以做你知道需要做的事情。

答案 1 :(得分:1)

解决这个问题的最基本方法是:

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