取消选择组合框选择的值

时间:2014-11-14 16:02:19

标签: vb.net

首先,我向社区道歉,因为标题可能看起来有点误导实际问题。 我已经制作了一个代码,用两个组合框填充相同的值,组合框中发生的每次更改都会检查选中的值是否等于另一个组合框;如果它相等,则执行特定代码,否则继续。 我需要实现取消选择价值,我用它做了:

ComboBox1.SelectedIndex = -1 
Combobox2.SelectedIndex = -1

这样可以正常工作,但检查值是否相等的代码会干扰此操作。 事实上,在每个组合框中我都有类似的东西:

Private Sub ComboBox2_SelectedIndexChanged_1(sender As Object, e As EventArgs) Handles ComboBox2.SelectedIndexChanged

If ComboBox3.SelectedIndex = ComboBox2.SelectedIndex Then
MsgBox ("You can not compare two equal teams", "Warning")
off ()
End If
...

其中“off()”是一个函数,然后不会继续你正在做的事情。 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

重置组合框时,您必须禁用该事件。这可以通过使用RemoveHandler / AddHandler删除事件并再次添加它来完成。

另一种选择是使用标志。 (这只是一个显示想法的示例,应该正确放置标志变量)。

Private FreezeEventFlag As Boolean = False ' or True, it depends..
' Declare it toplevel, initialize its value depending on
' the way you're going to initialize your Comboboxes selected values.
' Then set it's value to True each time you want to
' disable the event handling in any code block that resets
' SelectedIndexes to -1 like below :

    ' ...
    FreezeEventFlag = True
    ComboBox1.SelectedIndex = -1 
    Combobox2.SelectedIndex = -1
    FreezeEventFlag = False ' Don't forget to set the Flag to false !

Private Sub ComboBox2_SelectedIndexChanged_1(sender As Object, e As EventArgs) Handles ComboBox2.SelectedIndexChanged

    If FreezeEventFlag Then Exit Sub ' Just ignore this event this time.

    If ComboBox3.SelectedIndex = ComboBox2.SelectedIndex Then
        MsgBox ("You can not compare two equal teams", "Warning")
        off ()
    End If
End Sub