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.
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With