Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind Dictionary to ListBox in WinForms

Tags:

It is possible to bind a Dictionary to a Listbox, keeping in sync between the Listbox and the member property?

like image 805
ʞᴉɯ Avatar asked Oct 01 '09 23:10

ʞᴉɯ


2 Answers

var choices = new Dictionary<string, string>(); 
choices["A"] = "Arthur"; 
choices["F"] = "Ford"; 
choices["T"] = "Trillian"; 
choices["Z"] = "Zaphod"; 
listBox1.DataSource = new BindingSource(choices, null); 
listBox1.DisplayMember = "Value"; 
listBox1.ValueMember = "Key"; 

(Shamelessly lifted from my own blog: Bind a ComboBox to a generic Dictionary.)

This means you can use SelectedValue to get hold of the corresponding dictionary key for the selected item in the ListBox.

like image 134
Matt Hamilton Avatar answered Oct 03 '22 01:10

Matt Hamilton


        label1.Text= listBox1.SelectedIndex.ToString();

        if ( listBox1.SelectedItem is KeyValuePair<int,DockStyle>)
        {

            var temp1 = (KeyValuePair<int, DockStyle>)listBox1.SelectedItem;
            label3.Text = temp1.Key.ToString();
            label4.Text = temp1.Value.ToString();


        }
like image 38
WINSH WINSH Avatar answered Oct 03 '22 03:10

WINSH WINSH