开发者

Stop comboBox's selectedIndexChanged event from firing when the form loads

I have a form with a ComboBox that provides a dropdownlist. On the comboBox's SelectedIndexChanged event, am running som开发者_开发知识库e 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?


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.


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);


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!


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.


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


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


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
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜