Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Cannot do Key-Value in a ListBox in WinForms

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.

like image 883
Mehmed Avatar asked Dec 26 '11 08:12

Mehmed


1 Answers

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"; 
like image 103
Chamika Sandamal Avatar answered Sep 19 '22 12:09

Chamika Sandamal