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

前端 未结 6 1115
闹比i
闹比i 2021-01-17 11:35

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.

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-17 11:51

    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 comboBoxOldValues = new Dictionary();
    

    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)
        {
            if (((List)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;
    }
    

提交回复
热议问题