How to bind Dictionary to ListBox in WinForms

前端 未结 3 1417
旧巷少年郎
旧巷少年郎 2020-11-30 04:25

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

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 04:40

    var choices = new Dictionary(); 
    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.

提交回复
热议问题