Tuesday, September 25, 2007

Selecting Combobox item programmatically

Scenario:

I have added items to my combobox using combobox.Items.Add(obj), but when I set combobox.SelectedValue = selectedId, I still get null value in combobox.SelectedValue, though I've set combobox.ValueMember.

Solution:

Finally, I've found that ValueMember is respected only in data binding case only, whereas DisplayMember works in both cases -- Databinding and normal item addition.

In order to use SelectedValue, we need to bind the datasource to the combobox. Otherwise, we can use the following method to select the combobox item:

cboCategory.SelectedIndex = cboCategory.FindString(category);

FindString only search for DisplayMember only, but not ValueMember.


I guess the better solution is to do a databinding, but at the moment, I'll just use this alternative way of selecting items.

2 comments:

  1. what is the other way to select? i.e when the combobox is databinded?

    ReplyDelete
  2. Thanks Mate. I searched google a lot and find your relevant answer only in your post.

    ReplyDelete