Set SelectedItem on a combobox bound to datasource

懵懂的女人 提交于 2019-12-08 15:11:43

问题


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? Tried comboBox.SelectedItem = someCustomer; ...and lots of other stuff but no luck so far...


回答1:


You should do

comboBox.SelectedValue = "valueToSelect";

or

comboBox.SelectedIndex = n;

or

comboBox.Items[n].Selected = true;



回答2:


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. Open it from menu View > Other Windows > Data Sources. Add an Object data source of Customer type. 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. Visual Studio automatically adds A BindingSource and a BindingNavigator component to your form when you drop the first control. The BindingNavigator is optional and you can safely remove it, if you don't need it. Visual Studio also does all the wire-up. You can tweak it through the properties window. Sometimes this is required for combo boxes.

There's only one thing left to do in your code: Assign an actual data source to the binding source:

customerBindingSource.DataSource = _customers;



回答3:


this works for me

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


来源:https://stackoverflow.com/questions/10015942/set-selecteditem-on-a-combobox-bound-to-datasource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!