在绑定到数据源的combobox上设置SelectedItem

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

现在如何将combobox的项目设置为列表中第一个以外的其他项目? 尝试过comboBox.SelectedItem = someCustomer; ……还有很多其他东西,但到目前为止没有运气……

你应该做

 comboBox.SelectedValue = "valueToSelect"; 

要么

 comboBox.SelectedIndex = n; 

要么

 comboBox.Items[n].Selected = true; 

您的绑定代码不完整。 试试这个:

 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的“数据源”窗口中添加数据源。 从菜单视图>其他Windows>数据源中打开它。 添加Customer类型的Object数据源。 在数据源中,您将看到客户的属性。 通过右键单击属性,您可以更改与其关联的默认控件。

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

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

 customerBindingSource.DataSource = _customers;