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.
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;
}