检测是否单击组合框而不使用SelectedIndexChange

时间:2016-07-11 18:07:45

标签: vb.net

我想询问VB.net应用程序是否有可能在不使用SelectedIndexChange的情况下检测组合框是否已更改。

例如,我的应用程序有4个组合框,这个组合框是从用户配置动态创建的。 (该工具在启动应用程序时自动创建组合框)。然后,一旦应用程序启动,我想每次更改组合框时运行SUB。急需帮助。 TIA

1 个答案:

答案 0 :(得分:0)

If you are creating controls dynamically, you should add the event handlers dynamically as well. There is nothing wrong with using the SelectedIndexChanged event.

You can test this by making a new project and pasting this code inside Public Class Form1.

Private myComboBox1 As ComboBox
Private myComboBox2 As ComboBox

Private Shared selectedIndexChanged As EventHandler =
    Sub(sender As Object, e As EventArgs)
        Dim myComboBox = DirectCast(sender, ComboBox)
        ' alert the user as to what was selected
        MessageBox.Show(String.Format("{0} value: {1}, index: {2}",
                        myComboBox.Name, myComboBox.Text, myComboBox.SelectedIndex))
        ' you can do something different on each one by name in a case statement
        Select Case myComboBox.Name
            Case "myComboBox1"
                ' do something for 1
            Case "myComboBox2"
                ' do something for 2
        End Select
    End Sub

Private Sub addHandlers()
    AddHandler myComboBox1.SelectedIndexChanged, selectedIndexChanged
    AddHandler myComboBox2.SelectedIndexChanged, selectedIndexChanged
End Sub

Private Sub removeHandlers()
    RemoveHandler myComboBox1.SelectedIndexChanged, selectedIndexChanged
    RemoveHandler myComboBox2.SelectedIndexChanged, selectedIndexChanged
End Sub

Form eventhandlers

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ' dynamically generate combo boxes
    myComboBox1 = New ComboBox() With {.Name = "myComboBox1",
                                       .Left = 30,
                                       .Top = 30}
    myComboBox2 = New ComboBox() With {.Name = "myComboBox2",
                                       .Left = 30,
                                       .Top = 60}
    ' add some items
    myComboBox1.Items.AddRange({1, 2, 3})
    myComboBox2.Items.AddRange({"four", "five", "six"})
    ' add the combo boxes to the form
    Me.Controls.Add(myComboBox1)
    Me.Controls.Add(myComboBox2)
    ' add event handlers
    addHandlers()
End Sub

Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
    removeHandlers()
End Sub