为什么在加载表单之前调用 ComboBox SelectedIndexChanged? [英] Why is ComboBox SelectedIndexChanged being called before form load?

查看:23
本文介绍了为什么在加载表单之前调用 ComboBox SelectedIndexChanged?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

why Private Sub combobox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles combobox.SelectedIndexChanged called before form appears? In my understanding, this function should be called ONLY when user change the selected index of mycombobox? Am I wrong?

如何阻止它自动运行?

推荐答案

您可以使用布尔标志指示何时安全"处理事件,或者您可以使用替代语法在事件处理之后添加事件处理程序表单已加载,所有初始化都已完成.

You could either use a Boolean flag indicating when it is "safe" to handle the event, or you could use the alternative syntax to add your event handler AFTER the Form is loaded and all the initialization has been done.

为此,您使用 AddHandler 语法:

For this you use the AddHandler syntax:

AddHandler combobox.SelectedIndexChanged, AddressOf combobox_SelectedIndexChanged

希望能帮到你

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

Using the AddHandler syntax, you must make sure NOT to add the Handles clause to your event handler declaration:

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

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

Then, typically at the end of the Form's OnLoad override, you'll use the 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

这篇关于为什么在加载表单之前调用 ComboBox SelectedIndexChanged?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆