views:

1709

answers:

4

Hi

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

A: 

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()));
  }
mickyjtwin
But then, you'd have to parse the string values to retrieve the key or value separately elsewhere. Also, you'd loose data binding.
Dennis Palmer
+1  A: 

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); }
    }
}
Brandon Grossutti
A: 

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

AppDeveloper
No need to derive a custom listbox. Just handle DrawItem event.
Dennis Palmer
+3  A: 

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);
Adam Ruth
Thank You!! It worked beautifully!
Ashish