以编程方式更改Combobox选择而不会导致SelectedIndexChanged触发

时间:2013-02-22 10:57:01

标签: .net vb.net visual-studio-2005

所以我有一个带有SelectedIndexChanged事件处理程序的组合框:

    Private Sub cmbStatus_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbStatus.SelectedIndexChanged
        DoAnnoyingStuff()
        '....
    End sub

在我的表单中,我有一个执行此操作的函数(在一些用户交互之后):

Sub RefreshStatus()
    Dim sel As Int32 = GetNewStatus()
    cmbStatus.SelectedIndex = sel   '<-- fires a SelectedIndexChanged event that I don't need
End Sub

我想在RefreshStatus()中做的是更改组合框中显示的选择,但不执行DoAnnoyingStuff()。我该怎么做?

2 个答案:

答案 0 :(得分:1)

添加标志。因此,您将拥有一个名为_inChange As Boolean的私有类字段,然后在RefreshStatus开头将字段设置为true,并在结尾处设置为false。在cmbStatus_SelectedIndexChanged中,检查_inChange是否为true。如果是你就退出。如果为false,则继续并执行AnnoyingStuff。

答案 1 :(得分:1)

您可以手动管理事件,启用和禁用处理程序:

AddHandler cmbStatus.SelectedIndexChanged, AddressOf cmbStatus_SelIndexChg
RemoveHandler cmbStatus.SelectedIndexChanged, AddressOf cmbStatus_SelIndexChg    

如上所述,你可以使用一个标志:

Dim bRefreshStatus As Boolean = False

Private Sub cmbStatus_SelIndexChg(sender As Object, e As EventArgs) Handles cmbStatus.SelectedIndexChanged
    If Not bRefreshStatus Then DoAnnoyingStuff()
End Sub

Sub RefreshStatus()
    Dim sel As Int32 = GetNewStatus()
    bRefreshStatus = True
    cmbStatus.SelectedIndex = sel
    bRefreshStatus = False
End Sub