![](/img/trans.png)
[英]Bound Combobox changing SelectedItem when (re)filling Datasource
[英]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";
现在如何将组合框的 Item 设置为列表中第一个以外的其他内容? 试过 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 的“数据源”window 中添加一个数据源。 从菜单View > Other Windows > Data Sources打开它。 添加Customer
类型的Object数据源。 在数据源中,您将看到客户的属性。 通过右键单击属性,您可以更改与其关联的默认控件。
现在您只需将属性从数据源 window 拖到您的表单中。 当您放下第一个控件时,Visual Studio 会自动将BindingSource
和BindingNavigator
组件添加到您的窗体。 BindingNavigator
是可选的,如果不需要,您可以安全地删除它。 Visual Studio 也完成所有的连接工作。 您可以通过属性 window 对其进行调整。有时组合框需要这样做。
您的代码中只剩下一件事要做:将实际数据源分配给绑定源:
customerBindingSource.DataSource = _customers;
这对我有用
bsCustomers.Position = comboBox.Items.IndexOf(targetCustomer);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.