Reputation: 1631
Below is my code , List_sheet_name is a combo box
List_sheet_name.Items.Clear();
List_sheet_name.Items.Insert(0,"Select a table from Sheet");
for (int i = 0; i < Sheets.Rows.Count; i++)
{
List_sheet_name.Items.Add(Sheets.Rows[i]["TABLE_NAME"].ToString());
}
List_sheet_name.SelectedIndex = 0;
//List_sheet_name.SelectedIndex = List_sheet_name.FindStringExact("Select a table from Sheet");
After setting the SelectIndex to zero (in last two lines) it is automatically invoking the SelectedIndexChanged event too. Can someone tell me why this is happening ?
Upvotes: 0
Views: 79
Reputation: 540
According to the MSDN, the event reacts to all SelectedIndex
changes. If you change the index to a new value which is equal to the previous one, the event won't be fired again, you need to call it manually.
If you don't want the SelectedIndexChanged
event to be invoked when setting the SelectedIndex
, you should check in the SelectedIndexChanged
event whether the sender object (which is the ComboBox
) is focused.
private void YourComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (!(sender as ComboBox).Focused)
return;
// ...your code
}
Upvotes: 1
Reputation: 7325
Initially, it is -1. If you set to 0, then SelectedIndexChanged will be invoked.
Each time you set it to ANOTHER value, the SelectedIndexChanged will be raised. For set from codebehind you can use a variable bool _codeBehind, set it before you change SelectedIndex and evaluate in an Event handler
private bool _cmbSelIdxIntern = false;
void YourMeth()
{
_cmbSelIdxIntern = true;
cmbTest.SelectedIndex = 0;
_cmbSelIdxIntern = false;
}
private void cmbTest_SelectedIndexChanged(object sender, EventArgs e)
{
if (_cmbSelIdxIntern)
{
return;
}
}
Upvotes: 1