事件在您不希望触发时触发是 Windows 窗体中的常见问题 - SelectedIndexChanged 就是一个典型示例。我经常使用的一种方法是声明在运行部分代码时设置的标志,我知道当我不想听它时会触发事件。
一个例子:
Public Class Form1
Private m_IsSettingDataSource As Boolean = False
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Me.m_IsSettingDataSource = True
combobox_process.DataSource = DataView
combobox_process.DisplayMember = "UserDefine1"
combobox_process.SelectedIndex = -1
Catch
Throw
Finally
Me.m_IsSettingDataSource = False
End Try
End Sub
Private Sub combobox_process_SelectedIndexChanged(sender As Object, e As EventArgs) Handles combobox_process.SelectedIndexChanged
If Not Me.m_IsSettingDataSource Then
' Do what you want to do when not setting data source
End If
End Sub
End Class
您可以这样做,或者像约翰所说的那样,关闭并打开事件处理程序。当您知道两个或多个事件处理程序将受到影响时,标志方法可能会更好。