简体   繁体   中英

Executing an action only when I select an item form the combo box

I have a ComboBox and in the form's load event it's populated with data. Now when I select an Item form the ComboBox , it should perform some actions. So I know few events which can be used in this case like

SelectedIndexChanged

SelectedValueChanged

etc.

But the problem is those events are raised even when setting the DataSource of the ComboBox and selecting a default index etc. when the form is loaded.

    ComboBox1.DataSource = dt;

    ComboBox1.SelectedIndex = -1;

What am I trying to do is that I just want to execute an action only when I select an item form the combo box. Is there a mouse event that could be used in this case?

The comboBox.SelectionChangeCommitted Event seems to do that.

Otherwise you could set a boolean value before you bind the datasource which you can use inside the event to ignore it.

private bool blnIgnoreEvent = false;

// in Form_load
blnIgnoreEvent = true;
ComboBox1.DataSource = dt;
blnIgnoreEvent = false;

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (!blnIgnoreEvent)
    {
        // go ahead
    }
}

I don't believe there is another event that better handles what you'd like to do. XIVSolutions has a neat work-around for the event firing when you bind the data source: How to prevent selectedindexchanged event when DataSource is bound?

Also, since SelectedIndexChanged works for all cases, why not just handle the first?

if (ComboBox1.SelectedIndex == -1)
  {
    return;
  }

If -1 corresponds to a value you'd like to be able to select, just use a private field to store some bool that you check to determine whether or not it is the first time the action has been executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM