在绑定到数据源的组合框上设置SelectedItem

时间:2012-04-04 17:04:14

标签: c# combobox datasource selecteditem

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 个答案:

答案 0 :(得分:13)

你应该做

comboBox.SelectedValue = "valueToSelect";

comboBox.SelectedIndex = n;

comboBox.Items[n].Selected = true;

答案 1 :(得分: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的“数据源”窗口中添加数据源。从菜单中打开查看&gt;其他Windows&gt;数据源。添加Customer类型的对象数据源。在数据源中,您将看到客户的属性。通过右键单击属性,您可以更改与其关联的默认控件。

现在您只需将属性从“数据源”窗口拖到窗体即可。删除第一个控件时,Visual Studio会自动将A BindingSourceBindingNavigator组件添加到表单中。 BindingNavigator是可选的,如果您不需要,可以安全地将其删除。 Visual Studio也可以完成所有的连接。您可以通过属性窗口调整它。有时这是组合框所必需的。

您的代码中只剩下一件事:将实际数据源分配给绑定源:

customerBindingSource.DataSource = _customers;

答案 2 :(得分:0)

这对我有用

bsCustomers.Position = comboBox.Items.IndexOf(targetCustomer);
相关问题