Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 442
Ashish Avatar asked Jan 29 '26 00:01

Ashish


1 Answers

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);
}
like image 144
Adam Ruth Avatar answered Feb 01 '26 00:02

Adam Ruth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!