6

I have two items with the same DisplayMember, but a different ValueMember and want to select one of the two items programmatically, how do I do this?

Items:

123 -> Peter Pan
234 -> John Doe
345 -> Peter Pan

I cannot select the last "Peter Pan" by doing

Listbox1.FindStringExact("Peter Pan");

Because this only returns the first occurrence of "Peter Pan". The following also doesn't work because it only sets the selected item, but doesn't show it in the list:

Listbox1.SelectedItem = dataTable.Rows.Find(345);

Who can help me with this one?

I found some more info myself, the list is sorted, therefore when I update the DataTable (which is used to fill the list) the list is resorted and it seems to select the item that was in place of the edited item.

Listbox1.FindStringExact does only work if the DisplayMember is different.

Kate Orlova
  • 3,225
  • 5
  • 11
  • 35

2 Answers2

4

You can use the SelectedValue property of your list control:

Listbox1.SelectedValue = 345;
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • this doesn't work either, because then the list still takes the selected index and selects that item (the list is sorted) – Michael van der Horst Feb 07 '11 at 13:50
  • @Michael, `SelectedIndex` does what you say, `SelectedValue` is supposed to lookup the item from its `ValueMember` property. Did you try it? – Frédéric Hamidi Feb 07 '11 at 13:53
  • @Frédéric The list is sorted, therefore when i change the SelectedValue, the SelectedIndexChanged event fires, I then get the selectedRow by ListBox1.SelectedItem, this returns the selected item item in the list with the index of the selectedvalue, just before that, the sorting changed the way the list is sorted and therefore getting the wrong row – Michael van der Horst Feb 07 '11 at 13:58
  • @Michael, if I understand your issue correctly, you can fetch the selected row with `selectedRow = dataTable.Rows.Find(Listbox1.SelectedValue);`. – Frédéric Hamidi Feb 07 '11 at 14:03
  • @Frédéric, I know how to fetch the selected row, only when i update the row and the list updates itself, it has the item that was on that place selected. – Michael van der Horst Feb 07 '11 at 14:17
  • @Michael, I'm not sure to understand, so let's recap: 1) you get the currently selected item (how?), 2) you modify the associated row in the `DataTable`, 3) the list box updates that item's position, so another item gets selected, 4) you want to reselect the item you just modified? – Frédéric Hamidi Feb 07 '11 at 14:30
2

You must assign data via DataSource property of ListBox control, not via Items.Add. After that you can use ValueMember to select items:

listBox1.DataSource = GetPeople();
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "Id";

// Now you can use
listbox1.SelectedValue = 345;

UPDATE: Items is a member of ListBox class, but SelectedValue is a ListControl property, which can use only DataSource.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459