取消选择组合框项目 [英] Deselect combobox item

查看:61
本文介绍了取消选择组合框项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据绑定组合框:

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

当表单加载时,两个项目均未选中,但用户选择了一项不能取消选择。我试图添加 cmbbx_Managers.items.Insert(0, none),但是它不能解决问题,因为不可能向数据绑定中添加新项目

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.

我如何允许用户取消选择 combobox 项目?

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

推荐答案

要将项目添加到数据绑定的ComboBox,需要将您的项目添加到绑定到ComboBox的列表中。

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;

因此,要取消选择,您现在只需设置 ComboBox.SelectedIndex = 0 ,否则,请使用 BindingSource.CurrencyManager

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

此外,还需要根据@RamonAroujo从他的评论中给我们带来的精度,在最后一行设置DataSource属性。我相应地更新了答案。

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.

这篇关于取消选择组合框项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆