How can I handle ComboBox selected index changing?

前端 未结 10 1188
花落未央
花落未央 2020-12-21 06:10

I have a ComboBox that have a list of manufacturers. When a user selects a manufacturer, a grid below is populated with data for the chosen manufacturer. That data can be mo

10条回答
  •  囚心锁ツ
    2020-12-21 07:00

    I know this is an older question but I thought I'd add the method that I used. I'm not sure if it's any better. There should be a IndexChanging event or something in the regular ComboBox that can be cancelled.

    The solution is a combination of @AftabAhmedKalhoro's and @jeffamaphone's posts but using the Tag property instead.

    I didn't want to sub class the ComboBox, or have any extra private variables floating around in the form. But some might not like the Tag property, because it is kind of hidden if you're not use to using it (kind of left over from VB6).

    Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ComboBox1.Items.Add("Item1")
        ComboBox1.Items.Add("Item2")
        ComboBox1.Items.Add("Item3")
        ComboBox1.Items.Add("Item4")
        ' Load Value from database or whatever and set the value or index.
        ComboBox1.SelectedIndex = 0
        ComboBox1.Tag = ComboBox1.SelectedIndex
    
        ' I add the handler at the end because I don't want it to fire during loading the form.
        AddHandler ComboBox1.SelectedIndexChanged, New EventHandler(AddressOf ComboBox1_SelectedIndexChanged)
    End Sub
    
    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If (ComboBox1.Tag <> ComboBox1.SelectedIndex) Then
            If MessageBox.Show("Warning! You are changing the index." & vbCrLf & _
                               "Do you wish to continue?", _
                               "Changing Index", _
                               MessageBoxButtons.YesNo, _
                               MessageBoxIcon.Warning) = Windows.Forms.DialogResult.Yes Then
                ComboBox1.Tag = ComboBox1.SelectedIndex
                ' Do Something.
            Else
                ComboBox1.SelectedIndex = ComboBox1.Tag
            End If
        End If
    End Sub
    

    Note that resetting the SelectedIndex will cause the event to fire again in this line:

    ComboBox1.SelectedIndex = ComboBox1.Tag
    

提交回复
热议问题