Combobox SelectedItem

  • Thread starter Thread starter Robert
  • Start date Start date
R

Robert

I am trying to set a Combobox's SelectedItem property to an object but
without any success.
Code Example:
for (int i = 1; i < 10; i++)
{
Person p = new Person("JDoe" + i.ToString());
Combobox1.Items.Add(p);
}

Person findP = new Person ("JDoe5");
Combobox1.SelectedItem = findP;

The combobox does not set the SelectedItem when I run the above code.
Obviously I'm missing something and any help is appreciated.
 
I am trying to set a Combobox's SelectedItem property to an object but
without any success.
Code Example:
for (int i = 1; i < 10; i++)
{
Person p = new Person("JDoe" + i.ToString());
Combobox1.Items.Add(p);
}

Person findP = new Person ("JDoe5");
Combobox1.SelectedItem = findP;

The combobox does not set the SelectedItem when I run the above code.
Obviously I'm missing something and any help is appreciated.

It doesn't work because the object that findP references is not in the
combobox. It was created the same as one that is there, but it is a
different object. You must use the same object.

Since you know you want to select the 5th one, I would use:
Combobox1.SelectedIndex = 5-1;

If you don't know ahead of time which one you want:

int selIndx = -1;

for (int i = 1; i < 10; i++)
{
Person p = new Person("JDoe" + i.ToString());
Combobox1.Items.Add(p);
if ( ... )
selIndx = i - 1; /* Select this one */
}
Combobox1.SelectedIndex = selIndx;

Both examples assume that the combobox is empty before the loop.
Another possibility is to save p in another variable inside the loop
and set SelectedItem to the saved variable. I would presume that
using SelectedIndex would be more efficient than SelectedItem, since I
figure SelectedItem must sequentially examine each item in the list.
 
Back
Top