How to display a Dictionary in a ListBox

拜拜、爱过 提交于 2019-12-21 22:06:58

问题


I'm trying to display Key/Value Pairs from a Dictionary to a ListBox.

Key Value
A    10
B    20
C    30

I want to display them in a ListBox in following format

A(10)
B(20)
C(30)

Using following code I have been able to link Listbox.Datasource to Dictionary.

myListBox.DataSource = new BindingSource(myDictionary, null);

Its being displayed as

[A, 10]
[B, 20]
[C, 30]

I can't figure out how to format it so that it is displayed in the way I want.

Any help will be appreciated.

Thanks Ashish


回答1:


Use the Format event on the list box:

KeyValuePair<string, int> item = (KeyValuePair<string, int>)e.ListItem;
e.Value = string.Format("{0}({1})", item.Key, item.Value);



回答2:


For proper long term flexiblitity I would try and use a typed object, then you can do what ever you like later, raise events, change the values, not have to use unique keys, get a real object from listbox rather than just a formatted string

public partial class tester : Form
{
    public tester()
    {
        InitializeComponent();
         List<MyObject> myObjects = new List<MyObject>();
        MyObject testObject = new MyObject("A", "10");
        myObjects.Add(testObject);
       BindingSource bindingSource = new BindingSource(myObjects,null);
        listBox1.DisplayMember = "DisplayValue";
        listBox1.DataSource = bindingSource;
    }
}

public  class MyObject
{
    private string _key;
    private string _value;

    public MyObject(string value, string key)
    {
        _value = value;
        _key = key;
    }

    public string Key
    {
        get { return _key; }
    }

    public string Value
    {
        get { return _value; }
    }

    public string DisplayValue
    {
        get { return string.Format("{0} ({1})", _key, _value); }
    }
}



回答3:


You could iterate over the dictionary object and build the listbox item as you go.

  foreach (KeyValuePair<string, int> kvp in myDictionary)
  {
      lbx.Items.Add(String.Format("{0}({1})", kvp.Key, kvp.Value.ToString()));
  }



回答4:


Actually if you would like to customize list box derive from it and override

protected override OnDrawItem

Answer 1 will get what you stated in the question but if you want to reflect changes in the objects it would be better if you wrote the drawing routine so it would automatically reflect.

or you can change Text of item which would also do the trick.

Don't forget to call BeginUpdate() and EndUpdate()



来源:https://stackoverflow.com/questions/885271/how-to-display-a-dictionary-in-a-listbox

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