Search code examples
dictionarylistbox

How to display a Dictionary in a ListBox


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


Solution

  • Use the Format event on the ListBox:

    #1). Register the event:

    myListBox.Format += myListBox_Format;
    

    #2). Handle the event. Set Value property of the passed-in ListControlConvertEventArgs to the string to be displayed for a list item. According to Microsoft's documentation of the Event: "The Format event is raised before each visible item in the ListControl is formatted".

    private void myListBox_Format(object sender, ListControlConvertEventArgs e)
    {
        KeyValuePair<string, int> item = (KeyValuePair<string, int>)e.ListItem;
        e.Value = string.Format("{0}({1})", item.Key, item.Value);
    }