PDA

View Full Version : I'm Stumped!! C# question.


Kreij
02-15-2008, 09:10 PM
Ok, here's the deal ...

I have a windows form with a ComboBox on it (comboBox1).
I create an instance of a generic List of KeyValuePairs that contain an integer and a string

List<KeyValuePair<int, string>> cbData = new List<KeyValuePair<int,string>>();


I then create a few KeyValuePairs that go into the list

KeyValuePair<int, string> itemData;

int[] intArray = new int[3] { 3, 5, 7 };
string[] strArray = new string[3] { "hello", "wait", "goodbye" };
for (int i = 0; i < 3; i++)
{
itemData = new KeyValuePair<int, string>(intArray[i], strArray[i]);
cbData.Add(itemData);
}


I then Bind the List of KeyValuePairs to the Combobox


comboBox1.ValueMember = "Key";
comboBox1.DisplayMember = "Value";
comboBox1.DataSource = cbData;


By Binding the ComboBox to the List, it creates three items in the ComboBox.
The ComboBox Items basically look like this...

Item index ValueMember DisplayMember
0 3 Hello
1 5 Wait
2 7 Goodbye


Ok, now what I want to be able to do, is programmatically select the ComboBox index (so it shows the correct choice in the CB) based on the value of the Key in the ComboBox.ValueMember property.

I want the code to return the Item index of the item that has a MemberValue equal to "5" (for instance; the code should return and index of 1) so that I can set the ComboBox's selected index.

comboBox1.SelectedIndex = ???????


Anyone have any idea how to do this?

Do I have to create a Predicate<T> method and use the generic List's FindIndex method?
(Since the List's indexes are the same as the ComboBox's)

Can it even be done?

Thanks.

Oliver_FF
02-16-2008, 02:01 PM
Is this what you mean:

foreach (KeyValuePair<int, string> row in comboBox1.Items)
{
if (row.Key == 5)
{
comboBox1.SelectedIndex = comboBox1.Items.IndexOf(row);
}
}

or have I gotten the wrong end of the stick? :p

Kreij
02-18-2008, 02:56 PM
Is this what you mean:

foreach (KeyValuePair<int, string> row in comboBox1.Items)
{
if (row.Key == 5)
{
comboBox1.SelectedIndex = comboBox1.Items.IndexOf(row);
}
}

or have I gotten the wrong end of the stick? :p


Nope you hit the nail square on the head. Thank you very much.
I was stuck in the mode of thinking of the ComboBox Items as their Member and Value properties, and not the fact I could look at the orginal object (KeyValuePair) directly.

I also added a break statement after the SelectIndex statement so that the loop would end after it found the correct entry, instead of traversing the entire list.