绑定数据源的下拉框如何设置选中项?

14
List<Customer> _customers = getCustomers().ToList();
BindingSource bsCustomers = new BindingSource();
bsCustomers.DataSource = _customers;
comboBox.DataSource = bsCustomers.DataSource;
comboBox.DisplayMember = "name";
comboBox.ValueMember = "id";

现在我要如何将下拉框的项目设置为列表中除第一个以外的其他项目? 尝试过 comboBox.SelectedItem = someCustomer; ...以及其他很多方法,但到目前为止都没有成功...

3个回答

14

你应该这样做

comboBox.SelectedValue = "valueToSelect";
或者
comboBox.SelectedIndex = n;
或者
comboBox.Items[n].Selected = true;

comboBox.Items[n].Selected = true; 对我不起作用(可能是CF问题),但SelectedValue可以,我之前尝试过,但使用了错误的值。谢谢。 - mdc
我想指出的是,为了使这个工作正常,我不仅需要指定对象,还需要指定值成员字段。所以在上面的客户案例中,我必须使用 comboBox.SelectedValue = customerToSelect.id - AdamMc331

2
您的绑定代码不完整。请尝试以下内容:
BindingSource bsCustomers = new BindingSource();
bsCustomers.DataSource = _customers;

comboBox.DataBindings.Add(
    new System.Windows.Forms.Binding("SelectedValue", bsCustomers, "id", true));
comboBox.DataSource = bsCustomers;
comboBox.DisplayMember = "name";
comboBox.ValueMember = "id";

在大多数情况下,您可以在设计师中完成此任务,而不是在代码中进行操作。
首先,在Visual Studio的“数据源”窗口中添加一个数据源。从菜单“视图>其他窗口>数据源”中打开它。添加一个Customer类型的对象数据源。在数据源中,您将看到客户的属性。通过右键单击属性,您可以更改与其关联的默认控件。
现在,您只需从数据源窗口将属性拖动到表单中即可。当您放置第一个控件时,Visual Studio会自动向您的表单添加一个BindingSource和一个BindingNavigator组件。 BindingNavigator是可选的,如果您不需要它,则可以安全地删除它。 Visual Studio还会执行所有的连接工作。您可以通过属性窗口进行微调。有时,这对于组合框是必需的。
在您的代码中只剩下一件事要做:将实际数据源分配给绑定源:
customerBindingSource.DataSource = _customers;

为什么它会在comboBox.ValueMember = "id"时崩溃? - mdc
2
我建议您在设计器中将 BindingSource 添加为组件(请参见 ToolboxData 部分)。然后,您可以通过属性窗口设置所有这些属性。如果您首先在 VS 的 Data Sources 窗口中定义对象数据源,则更容易。然后,您只需从此窗口将字段拖到表单上,绑定线路会自动完成。如果您这样做,BindingSourceBindingNavigator 将自动插入。然后,如果您不需要它,可以安全地删除 BindingNavigator - Olivier Jacot-Descombes
哪个属性或对象代表绑定的选定项?bsCustomers不是一个列表吗?它有多个“id”吗? - joe
数据源是一个 List<Customer>,其中 Customer 拥有 idname 属性。Customer.id 绑定到 ComboBox.SelectedValue 属性。 - Olivier Jacot-Descombes

1
这对我有效。
bsCustomers.Position = comboBox.Items.IndexOf(targetCustomer);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接