Reputation: 6247
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.
Upvotes: 0
Views: 8089
Reputation: 1042
Another way:
combobox.SelectedIndex = combobox.FindStringExact("myString")
Upvotes: 0
Reputation: 112895
Use ComboBox.SelectedIndex
.
E.g.:
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.
Upvotes: 1
Reputation: 14874
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;
Upvotes: 2
Reputation: 69282
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.
Upvotes: 3