3
votes

I have a databound combobox:

using(DataContext db = new DataContext())
{
    var ds = db.Managers.Select(q=> new { q.ManagerName, q.ManagerID});

    cmbbx_Managers.BindingContext = new BindingContext();
    cmbbx_Managers.DataSource = ds;
    cmbbx_Managers.DisplayMember = "ManagerName";
    cmbbx_Managers.ValueMember = "ManagerID";
}

When the form loads neither item is selected, but when the user chooses an item it cannot be deselected. I tried to add cmbbx_Managers.items.Insert(0, "none"), but it does not solve the problem, because it is impossible to add a new item to the databound combobox.

How do I allow a user to deselect a combobox item?

3
A separate button that assigns SelectedIndex to -1.paparazzo
I know that this is an old thread, but anyone that stumble here, mainly naive coders, probably, should go for Cody Gray's answer below to know why this is the wrong tool for this job...Marcelo Scofano Diniz

3 Answers

4
votes

To add an item to your databound ComboBox, you need to add your item to your list which is being bound to your ComboBox.

var managers = managerRepository.GetAll();

managers.Insert(0, new Manager() { ManagerID = 0, ManagerName = "(None)");

managersComboBox.DisplayMember = "ManagerName";
managersComboBox.ValueMember = "ManagerID";
managersComboBox.DataSource = managers;

So, to deselect, you now simply need to set the ComboBox.SelectedIndex = 0, or else, use the BindingSource.CurrencyManager.

Also, one needs to set the DataSource property in last line per this precision brought to us by @RamonAroujo from his comment. I updated my answer accordingly.

3
votes

The way you "deselect" an item in a drop-down ComboBox is by selecting a different item.

There is no "deselect" option for a ComboBox—something always has to be selected. If you want to simulate the behavior where nothing is selected, you'll need to add a <none> item (or equivalent) to the ComboBox. The user can then select this option when they want to "deselect".

It is poor design that, by default, a ComboBox appears without any item selected, since the user can never recreate that state. You should never allow this to happen. In the control's (or parent form's) initializer, always set the ComboBox to a default value.

If you really need a widget that allows clearing the current selection, then you should use a ListView or ListBox control instead.

3
votes

To deselect an item suppose the user presses the Esc key, you could subscribe to the comboxBox KeyDown event and set selected index to none.

private void cmbbx_Managers_KeyDown(object sender, KeyEventArgs e)
{
  if (e.KeyCode == Keys.Escape && !this.cmbbx_Managers.DroppedDown)
  {
    this.cmbbx_Managers.SelectedIndex = -1;
  }
}