ComboBox SelectedIndexChanged event: how to get the previously selected index?
Asked Answered
T

6

19

I have a user control which has a ComboBox and a SelectedIndexChanged event handler. In the event handler, I need to be able to tell what was the previously selected index... can anyone point me in the right direction?

private void cboTargetMode_SelectedIndexChanged(object sender, EventArgs e)
{
    // need to get the previously selected index and do some handling here...
    // ... some handler code here ...


    switch (cboTargetMode.SelectedIndex)
    {
        case 1:  // ..... some code here...
            break;
        case 2:  // ..... some code here...
            break;
        case 3:  // ..... some code here...
            break;
        default: // ..... some code here...
            break;
    }
}
Timbuktu answered 13/7, 2010 at 13:58 Comment(0)
P
26

There is nothing built in, you will need to listen for this event and keep track in an instance variable.

Use -1 as an uninitialized "last index", so on first pass you set it but don't use it. Subsequent passes you use it and set it.

You could always do this using a derived ComboBox class of your own and override OnSelectedIndexChanged and expose a PreviousSelectedIndex property. This way, it wouldn't be tightly coupled to the form. Alternatively, as you can do this using events, its also eligible for implementation as an extender provider.

Paphos answered 13/7, 2010 at 14:2 Comment(3)
Shouldn't it rather be "instance variable" instead of "class variable" ?Photolysis
@FrankSchmitt Chasing a badge dredging up a near 8 year old post? ;-) But yes you are correct, I've amended my answer.Paphos
@AdamHouldsworth Thanks. And no, I'm (currently) not on a badge hunt :-)Photolysis
J
3

I guess you will have to store the current (that will become the previous later on) into a variable so that it is used like a cache or something like so.

private void cboTargetMode_SelectedIndexChanged(object sender, EventArgs e) {
    // need to get the previously selected index and do some handling here...
    // ... some handler code here ...

    // Assuming that the variable PreviousSelectedIndex is declared in the class with value -1.
    if (PreviousSelectedIndex < 0)
        PreviousSelectedIndex = cbo.TargetMode.SelectedIndex;
    else
        // Do some handling here...

    switch (cboTargetMode.SelectedIndex) {
        case 1:  // ..... some code here...
            break;
        case 2:  // ..... some code here...
            break;
        case 3:  // ..... some code here...
            break;
        default: // ..... some code here...
            break;
    }
}

Is this something you have already thought of?

Otherwise, perhaps working with the Control.Validating event? I just can't say whether this event occurs before or after the SelectedIndexChanged event. =(

Joust answered 13/7, 2010 at 14:5 Comment(0)
S
0

how about the comboBox_SelectionChangeCommitted event? this is called after the selection is made, the menu is collapsed but the item is not compleetly changed. So just read comboBox.SelectedText or comboBox.SelectedValue and even comboBox.SelectedIndex

private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
{
    int prevIndex = comboBox1.SelectedIndex;
}
Stewartstewed answered 2/3, 2016 at 12:16 Comment(3)
@Zekeriya, this was from 6 years ago, but I resolved the problem by two-way binding the SelectedItem and managing the previous selection in the setter of the binded property on the view model. And truth be told, this turned out to be the better way, since it was easier to do, and was control-agnostic -- which meant that I didn't need to write some handler code for every different control that I would bind the list to.Timbuktu
Ok I needed a solutiion for this problem last month but the accepted awnser did not work for me. In some kind of way your current response also did not work but I will check it later on... Thanks for the response anyway :)Durban
The current MVVM philosophy that we are using @ my shop is to avoid converters, avoid behaviors (unless absolutely necessary) and try to get the viewmodel to do more work - i.e. make it provide the SelectedItem, etc.Timbuktu
P
0

This one to get the current selected index ,I just need it and I couldn't find anywhere ,so I hope it helps

 private void lsbx_layers_SelectedIndexChanged(object sender, EventArgs e)
        {
            int i = lsbx_layers.SelectedIndices[0];//selected index
            MessageBox.Show("Selected item at index : " + i);
        }
Prem answered 6/5, 2016 at 7:40 Comment(0)
V
0

I had a similar issue to this in which I set all my combo boxes to "autocomplete" using

ComboBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
ComboBox.AutoCompleteSource = AutoCompleteSource.ListItems;

I looped through and set all their lostFocus Events:

foreach(Control control in this.Controls)
{
    if(control is ComboBox)
   {
        ((ComboBox)control).LostFocus += ComboBox_LostFocus;
   }
}

and had a dictionary object to hold old values

public Dictionary<string, int> comboBoxOldValues = new Dictionary<string, int>();

then finally ensure the value exists or set to old index, then save to the dictionary

private void ComboBox_LostFocus(object sender, EventArgs e)
{
    ComboBox comboBox = (ComboBox)sender;

    if (comboBox.DataSource is List<YourDataType>)
    {
        if (((List<YourDataType>)comboBox.DataSource).Count(x => x.YourValueMember == (YourValueMemberType)comboBox.SelectedValue) == 0)
        {
            if (comboBoxOldValues.Keys.Count(x => x == comboBox.Name) > 0)
            {
                comboBox.SelectedIndex = comboBoxOldValues[comboBox.Name];
            }
            else
                comboBox.SelectedIndex = -1;
        }
    }            

    if (comboBoxOldValues.Keys.Count(x => x == comboBox.Name) > 0)
    {
        comboBoxOldValues[comboBox.Name] = comboBox.SelectedIndex;
    }
    else
        comboBoxOldValues.Add(comboBox.Name,  comboBox.SelectedIndex);

    if (comboBox.SelectedIndex == -1)
        comboBox.Text = string.Empty;
}
Volnak answered 14/8, 2017 at 22:42 Comment(0)
T
0

You can grab & store the old value in the DropDown event. Then revert to that old value in the SelectionChangeCommitted event (if warranted).

Thrawn answered 2/6, 2020 at 14:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.