简体   繁体   中英

c# select a value in combobox

My combobox in c# windows forms is filled with data from my database... Display Members are strings, value members are ints

I now have to preselect it before showing the form. I have tried:

combobox.DisplayMember = string;
combobox.Text = string;
combobox.SelectedItem = string;
combobox.SelectedText = string;
combobox.SelectedValue = string;

Anyone that can give me a little help? Would be much appriciated :-)

EDIT : ei. maybe solution for others... Remember that the load created by VS2010 designer is loaded after constructor. not within initializeComponents(), as I thought.

If your ComboBox is data-bound and you have properly set up the DisplayMember and ValueMember properties, then you can simply set the SelectedValue property to the value of the item you want to select.

For example, if you had the following objects in your combo box:

ID  Description
--  -----------------
2   Lorem
4   Ipsum
6   Dolor
8   Sit

You would set the DisplayMember to "Description" and ValueMember to "ID". Then in order to select the item "Dolor", you would just set SelectedValue = 6.

Find the Item then set the SelectedItem property of combobox to true.

EDIT:

comboBox.SelectedItem = comboBox.Items.Cast<string>().First(o => o == "blala");

use the Cast<string>() if your Items is string, Quick Qatching the combobox.Items will show you the object.

In a case that I can't remember exactly whether it was winforms or not, you should set the selected Item's selected property to false, then set another one to true.

check it and if that's the case just add this line:

combobox.SelectedIndex = -1;

Use ComboBox.SelectedIndex .

Eg:

myComboBox.SelectedIndex = [index of item to select];

Note that ComboBox.Items is an ObjectCollection , which has a method called IndexOf() . Pass it a reference to the object you want to select, and you should get the proper index back.

其他方式:

combobox.SelectedIndex = combobox.FindStringExact("myString")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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