为什么在表单加载之前调用ComboBox SelectedIndexChanged?

时间:2016-03-20 01:26:10

标签: vb.net combobox

为什么 Private Sub combobox_SelectedIndexChanged(sender As Object,e As EventArgs)处理在表单出现之前调用的combobox.SelectedIndexChanged ? 根据我的理解,当用户更改mycombobox的选定索引时,此功能应该被称为 ONLY ?我错了吗?

如何阻止它自动运行?

1 个答案:

答案 0 :(得分:1)

您可以使用布尔标志来指示何时“安全”来处理事件,或者您可以使用替代语法在加载窗体并完成所有初始化之后添加事件处理程序。

为此,您使用AddHandler语法:

AddHandler combobox.SelectedIndexChanged, AddressOf combobox_SelectedIndexChanged

希望这有帮助

编辑:

使用AddHandler语法,您必须确保不要将Handles子句添加到事件处理程序声明中:

Private Sub combobox_SelectedIndexChanged(sender As Object, e As EventArgs) 
'you event handler code
End Sub

然后,通常在表单的OnLoad覆盖结束时,您将使用AddHandler

Public Class Form1

    Protected Overrides Sub OnLoad(e As EventArgs)
        MyBase.OnLoad(e)

        ' Initialization code/whatever

        AddHandler ComboBox1.SelectedIndexChanged, AddressOf combobox_SelectedIndexChanged

    End Sub

    Private Sub combobox_SelectedIndexChanged(sender As Object, e As EventArgs)
    'Your event handler code
    End Sub

End Class