Cannot do key-value in listbox in C#

若如初见. 提交于 2020-01-11 05:02:06

问题


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";


来源:https://stackoverflow.com/questions/8634066/cannot-do-key-value-in-listbox-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!