I have a form with a ComboBox that provides a dropdownlist. On the comboBox's SelectedIndexChanged event, am running some code, but I don't want that code to run when the form loads. Unfortunately, when I load the form (before I make a selection in the combobox), SelectedIndexChanged of the combobox fires (I think when the combobox is databinding). Is there a way of avoiding such behaviour?
-
Not sure about on the desktop, but in .NET Compact, this event actually appears to fire before the Form_Load event, which is really problematic - nothing on the form is even set up yet when this code gets hit. On CF, the solution is unfortunately a form variable that gets set at the end of Load, and then the event handler checks for this variable before it fires.SqlRyan– SqlRyan2013-02-11 02:19:47 +00:00Commented Feb 11, 2013 at 2:19
7 Answers
If you want to react only when the user change the selected item in the combo box, then it is better to subscribe to SelectionChangeCommitted.
4 Comments
You can simply unbind the SelectedIndexChanged event, call your fill function and bind the SelectedIndexChanged event again. Unfortunately, this doesn't work with a grid.
For example:
this.cmb.SelectionChanged -= new System.EventHandler(this.cmb_SelectionChanged);
cmb.fill(); //Your function
this.cmb.SelectionChanged += new System.EventHandler(this.cmb_SelectionChanged);
Comments
Be sure to set the DataSource property in your onload() function after assigning the ValueMember and Datamember properties.
This will help you to solve your problem!
2 Comments
Why not have a boolean flag that indicates when your Form has finished loading?
In your SelectionChanged event, check if the boolean flag is true. If it is true then handle the event, otherwise ignore it.
4 Comments
ToolStripComboBox variation does not have a SelectionChangeCommitted event. So, this method will have to do. Or, to prevent race conditions, use lock and Monitor.TryEnter.Here is a simple solution that leaves your code almost untouched:
In the SelectedIndexChanged event, check if the myComboBox handle is created using the (IsHandleCreated) method. Another added check is to check if the user is actually focusing your combobox control to change selected index.
private void myComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (myComboBox.IsHandleCreated && myComboBox.Focused)
{
// Do something here
}
}
3 Comments
VB
RemoveHandler lbxNomes.SelectedIndexChanged, AddressOf lbxNomes_SelectedIndexChanged
lbxNomes.DataSource = dst
Label1.Text = String.Format("Encontrados {0} Sócios nesta pesquisa", dst.Rows.Count)
Label1.Visible = True
AddHandler lbxNomes.SelectedIndexChanged, AddressOf lbxNomes_SelectedIndexChanged
Comments
It worked for me in a way with the following code:
private void ddlChapter_SelectionChangeCommitted(object sender, EventArgs e)
{
if (ddlChapter.SelectedValue != null)
{
// Do something here
}
}