Combobox SelectedItem

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.
 
J

Jack Jackson

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top