9

I'm writing a C# app using a ListBox in WinForms.

I get my data (id and full name) from an XML file. I want to show full names in the listbox and when I select one of them, I want to get the relevant id.

I tried using SelectedValue property with no luck.

I also tried KeyValuePair and it shows "[full name, id]" in the listbox, which is not what I wanted:

LB_UserList.Items.Add(new KeyValuePair<string, string>(full_name, node["user_id"].InnerText));

How can I simulate a HTML select in C# in short? I want to show full names in the listbox and to get relevant id in the backend.

Mehmed
  • 2,880
  • 4
  • 41
  • 62
  • possible duplicate of [How do I get at the listbox item's "key" in c# winforms app?](http://stackoverflow.com/questions/507354/how-do-i-get-at-the-listbox-items-key-in-c-sharp-winforms-app) – Moshtaf Jul 27 '15 at 13:49

1 Answers1

19

use c# dictionary for this,

Dictionary<string, string> list = new Dictionary<string, string>();
list.Add("item 1", "Item 1");
list.Add("item 2", "Item 2");
list.Add("item 3", "Item 3");
list.Add("item 4", "Item 4");

dropdown.DataSource = list;
dropdown.DataTextField = "Value";
dropdown.DataValueField = "Key";
dropdown.DataBind();

EDIT:

listBox.DataSource = new BindingSource(list, null); 
listBox.ValueMember = "Key";
listBox.DisplayMember = "Value"; 
Ola Ström
  • 4,136
  • 5
  • 22
  • 41
Chamika Sandamal
  • 23,565
  • 5
  • 63
  • 86
  • 1
    DataTextField, DataValueField and DataBind is missing in ListBox in C#. For DataSource, I get this error: "Complex DataBinding accepts as a data source either an IList or an IListSource." However, thanks for the fast reply :) – Mehmed Dec 26 '11 at 09:02