Cannot do key-value in listbox in C#

2019-02-17 13:27发布

问题:

i'm writing a C# app using winforms. I have a listbox. I get my data from xml file, user name and their id's. I want names to be shown in the listbox and when I select one of them, I want to get his/her id using selectedValue property. However I cannot do this. I tried keyValuePair which shows "[username, id]" in the listbox which is not good (see code below). How can I simulate html select in c# in short? I want names to be shown in the listbox but want to get id's in the backend. Thanks...

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

回答1:

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.DisplayMember = "Key"; 
listBox.ValueMember = "Value";