1

I have several KeyValuePair in a combobx.

this.cbEndQtr.Items.Clear();
this.cbEndQtr.Items.Add(new KeyValuePair<int, string>(1, "Test1"));
this.cbEndQtr.Items.Add(new KeyValuePair<int, string>(2, "Test2"));

What's the simplest way to select the by passing in the key. For example something like this:

this.cbEndQtr.SelectedItem = 2;
Mikael Dúi Bolinder
  • 2,080
  • 2
  • 19
  • 44

2 Answers2

4

Here is a brute force approach:

void selectByKey(int key)
{
    foreach (var item in cbEndQtr.Items)
        if (((KeyValuePair<int, string>)item).Key == key) 
        {
            cbEndQtr.SelectedItem = item;
            break;
        }
}

And I just found this one line approach:

cbEndQtr.SelectedItem = cbEndQtr.Items.OfType<KeyValuePair<int, string>>().ToList().FirstOrDefault(i => i.Key == key);

Although if it doesn't find a match nothing will change.

Mikael Dúi Bolinder
  • 2,080
  • 2
  • 19
  • 44
MikeH
  • 4,242
  • 1
  • 17
  • 32
  • Nothing will change in your `for` loop, but your 'one line' approach sets the selected item to `null` if none is found. – Silvermind Feb 28 '14 at 23:30
  • @Silvermind `KeyValuePair` isn't nullable so you end up trying to set `SelectedItem` to a new instance of `KeyValuePair` (the default value). In my quick test if something was already selected it stayed selected. – MikeH Feb 28 '14 at 23:33
  • My bad, didn't notice that. – Silvermind Mar 01 '14 at 08:55
3

I think you can use LINQ like this:

var key = 2; // get key from somewhere

var items = this.cbEndQtr.Items.OfType<KeyValuePair<int, string>>()
             .Select((item,index) => new { item, index);

var index = items.Where(x => x.item.Key == key).Select(x => x.index).First();        

this.cbEndQtr.SelectedIndex = index;
Selman Genç
  • 100,147
  • 13
  • 119
  • 184