Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select ListBox item by ValueMember

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.

like image 305
Michael van der Horst Avatar asked Feb 07 '11 13:02

Michael van der Horst


2 Answers

You can use the SelectedValue property of your list control:

Listbox1.SelectedValue = 345;
like image 130
Frédéric Hamidi Avatar answered Sep 19 '22 13:09

Frédéric Hamidi


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.

like image 44
Sergey Berezovskiy Avatar answered Sep 19 '22 13:09

Sergey Berezovskiy