Reputation: 29159
Is it a way to refresh the items of a combo box and still keep the selected item so the SelectedIndexChanged
event will not be triggered? Even if the selected item is not in the new item list?
The following code seems will reset the selected item and trigger SelectedIndexChanged
event.
void RefreshComboboxItems()
{
var ds = GetRefreshedItems();
cb.DataSource = ds;
cb.DisplayMember = "Name";
cb.ValueMember = "Value";
}
// cb is already initialized and an item is selected
RefreshComboboxItems(); // Want to keep the selected item unchanged and don't trigger the event
Upvotes: 1
Views: 2816
Reputation: 216253
No, you could get the current SelectedValue, remove the Event Handler, refresh the combo, try to set again the SelectedValue with the saved value and then readd the Event Handler
void RefreshComboboxItems()
{
try
{
int currentValue = -1;
if(cb.SelectedValue != null)
currentValue = Convert.ToInt32(cb.SelectedValue);
cb.SelectedIndexChanged -= mySelectedIndexChangedMethod;
var ds = GetRefreshedItems();
cb.DataSource = ds;
cb.DisplayMember = "Name";
cb.ValueMember = "Value";
if(currentValue != -1)
cb.SelectedValue = currentValue;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cb.SelectedIndexChanged += mySelectedIndexChangedMethod;
}
}
Note that I have readded the event handler inside a finally to be sure that the event handler is readded to your combobox also in case an exception causes a premature exit from this code after removing the event handler
Upvotes: 2
Reputation: 460048
If you want to remove the event handler temporarily you could do:
void RefreshComboboxItems()
{
cb.SelectedIndexChanged -= Ddl_SelectedIndexChanged;
var ds = GetRefreshedItems();
cb.DataSource = ds;
cb.DisplayMember = "Name";
cb.ValueMember = "Value";
cb.SelectedIndexChanged += Ddl_SelectedIndexChanged;
}
Upvotes: 0