Deselect combobox item

陌路散爱 提交于 2019-12-13 16:19:28

问题


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?


回答1:


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.




回答2:


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:


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


来源:https://stackoverflow.com/questions/25328761/deselect-combobox-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!