简体   繁体   English

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

[英]Set SelectedItem on a combobox bound to datasource

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

Now how do I set the combobox's Item to something other than the first in the list?现在如何将组合框的 Item 设置为列表中第一个以外的其他内容? Tried comboBox.SelectedItem = someCustomer;试过 comboBox.SelectedItem = someCustomer; ...and lots of other stuff but no luck so far... ......还有很多其他的东西,但到目前为止还没有运气......

You should do你应该做

comboBox.SelectedValue = "valueToSelect";

or要么

comboBox.SelectedIndex = n;

or要么

comboBox.Items[n].Selected = true;

Your binding code is not complete.您的绑定代码不完整。 Try this:试试这个:

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

In most cases you can accomplish this task in the designer, instead of doing it in code.在大多数情况下,您可以在设计器中完成此任务,而不是在代码中完成。

Start by adding a data source in the "Data Sources" window in Visual Studio.首先在 Visual Studio 的“数据源”window 中添加一个数据源。 Open it from menu View > Other Windows > Data Sources .从菜单View > Other Windows > Data Sources打开它。 Add an Object data source of Customer type.添加Customer类型的Object数据源。 In the Data Sources you will see the customer's properties.在数据源中,您将看到客户的属性。 Through a right click on the properties you can change the default control associated to it.通过右键单击属性,您可以更改与其关联的默认控件。

Now you can simply drag a property from the Data Sources window to you form.现在您只需将属性从数据源 window 拖到您的表单中。 Visual Studio automatically adds A BindingSource and a BindingNavigator component to your form when you drop the first control.当您放下第一个控件时,Visual Studio 会自动将BindingSourceBindingNavigator组件添加到您的窗体。 The BindingNavigator is optional and you can safely remove it, if you don't need it. BindingNavigator是可选的,如果不需要,您可以安全地删除它。 Visual Studio also does all the wire-up. Visual Studio 也完成所有的连接工作。 You can tweak it through the properties window. Sometimes this is required for combo boxes.您可以通过属性 window 对其进行调整。有时组合框需要这样做。

There's only one thing left to do in your code: Assign an actual data source to the binding source:您的代码中只剩下一件事要做:将实际数据源分配给绑定源:

customerBindingSource.DataSource = _customers;

this works for me这对我有用

bsCustomers.Position = comboBox.Items.IndexOf(targetCustomer);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM