How to display a Dictionary in a ListBox

2020-07-24 04:48发布

问题:

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()