1

I'm trying to mark one of the combobox items as selected.

So I am building my combobox like this:

var drop = new Dictionary<int, string>();
while (RegReader.Read())
{
    drop.Add(Convert.ToInt32(RegReader["intRulesID"]), RegReader["txtName"].ToString());
}

RegRuleDrop.DataSource = new BindingSource(drop, null);
RegRuleDrop.DisplayMember = "Value";
RegRuleDrop.ValueMember = "Key";

Now, one of the items within the RegRuleDrop should be pre selected based on a value from a reader above this code. Now, the problem is that I need to select value based on the actual ListItem VALUE and not TEXT.

So as an example

drop.Add(1, "Test");
drop.Add(2, "Test2");
drop.Add(3, "Test3");

I need to find the index using 1,2 or 3 not Test, Test2 or Test3

Any ideas?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Arturs Kirsis
  • 129
  • 1
  • 1
  • 9
  • 1
    http://stackoverflow.com/questions/10160708/how-to-find-item-by-value-combobox-in-c-sharp. Same thing you're trying to do and also http://stackoverflow.com/questions/19786889/set-selected-item-in-combobox-vb-net –  Feb 25 '15 at 13:49
  • 1
    Not quite, all of the examples there are searching by DisplayMember when I need to perform search by ValueMember :( – Arturs Kirsis Feb 25 '15 at 13:50
  • Why do you need to search in the first place? If you want `id=2` to be selected, just save the index of the last item in the box after adding that item in the loop. – SimpleVar Feb 25 '15 at 13:52
  • 1
    Setting the SelectedValue property should be enough – Steve Feb 25 '15 at 13:52

1 Answers1

3

When you have the DataSource set to a BindingSource the only action needed to select an item given a value belonging to the ValueMember property is

drop.Add(1, "Test1");
drop.Add(2, "Test2");
drop.Add(99, "Test99");
drop.Add(3, "Test3");
.....

RegRuleDrop.SelectedValue = 99
Steve
  • 213,761
  • 22
  • 232
  • 286