3
votes

iam using combobox, not bounded to data source in c#.

cmbBox.Items.Add("apple");
cmbBox.Items.Add("orange");
cmbBox.Items.Add("banana");

Now I want to set SelectedIndex to finally added "banana", but cannot use cmbBox.SelectedIndex = cmbBox.Items.count -1; as the combo box is sorted !

Any tips please ?

4
@jeremy i used to use NewIndex in vb and was searching similar to it. I tried all expressions of indexof, selectedindex, selecteditem, combinations of them, and finally lost all direction/logic. Sorry, i didnot fill up this question with big story of struggle i had to find an answer and what i did/didn't do.Srikanth S

4 Answers

5
votes

Well i figured it out after refering the documentation. All tha i should have done is captured return value of cmbBox.Items.Add("something") statement and set it as cmbBox.SelectedIndex

nReturn = cmbBox.Items.Add("first");
...
nReturn = cmbBox.Items.Add("last");
cmbBox.SelectedIndex = nReturn;

Hope this helps some one.

3
votes

The following works for me

ComboBox cb = new ComboBox();
cb.Sorted = true;
cb.SelectedIndex = cb.Items.Add("apple");
cb.SelectedIndex = cb.Items.Add("orange");
cb.SelectedIndex = cb.Items.Add("banana");

After the last line selected index = 1 and selected item = banana

0
votes

It is even more simple than that. The index to the list in your case is "2" because the list is zero based and you added 3 items. So, count the number of items added to your list and subtract 1. 3 items, minus 1 = 2. Your last item added has a selectedindex of 2.

0
votes

It's quiet easy. Just use this...

cb.SelectedIndex = cb.Items.Count - 1;