12

I want my application to grab the value of a ComboBox and then to set the one chosen by the user or to somehow get the previously selected value.

The thing is that within my Form, there are four lists and a ComboBox (which contains all the values from the lists) and I want to repopulate the value of the ComboBox back to the list it was taken from and then remove the newly selected item from other/same list.

1 Answer 1

22

You want to handle the ComboBox.Enter event. Then save off the SelectedItem or SelectedValue to a member variable. Whenever you want then, you can re-assign that value to the ComboBox.

Register for the event. You can do this one of two ways:

Do it through the designer. Select your combo box. In the "Properties window", click the lightning bolt icon to show all of its events. Then find "Enter", and double-click in the box. It will automatically generate the callback function ("event handler") for you, and wire it up to the event.

enter image description here

enter image description here

You can programatically do the same thing. In the constructor, hook up an event handler of the correct signature:

public partial class Form1 : Form 
{
    public Form1()
    {
        InitializeComponent();
        comboBox1.Enter += comboBox1_Enter;
    }

    private void comboBox1_Enter(object sender, EventArgs e)
    {
        m_cb1PrevVal = comboBox1.SelectedValue;
    }

    private void RestoreOldValue()
    {
        comboBox1.SelectedValue = m_cb1PrevVal;
    }
}
5
  • events, never used them really... they seem scary :)
    – smsware
    Commented Jul 16, 2012 at 0:41
  • 4
    not at all... they're just a callback function. The control "calls back" to a function you tell it to, whenever a certain thing happens. Learn to use them now, because they're a critical part of WinForms (and c# in general, really) Commented Jul 16, 2012 at 0:42
  • 2
    for now I'm in love with C#'s design so I will trust the makers for making them critical... :)
    – smsware
    Commented Jul 16, 2012 at 0:48
  • oh my, it's really easy... thank you! I will totally get more info about those!
    – smsware
    Commented Jul 16, 2012 at 0:53
  • I can't find this event for WPF Combo box, any alternative event? Commented Nov 11, 2021 at 9:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.