jump to navigation

Data binding with generic dictionary objects January 30, 2009

Posted by gcorbin in .NET, ASP.NET, C#.
Tags: , ,
2 comments

This issue caused me some pain recently. So, after I spent some time to figure out how to do this, I figured it would be good to share it with the community. The problem is that I had to created my own class called Item. This class was meant to contain all properties and methods on an Item object. I then wanted to have a collection of Item objects, so I created a generic dictionary that contained the Item object as the Kvalue for the generic dictionary. The problem comes when you try to databind this collection to a control.

 

Many of the WinForm controls only support databinding to an IList. To make the generic dictionary work here, we need to use the BindingSource Object (BindingSource implements IList). The next trick is that the DisplayMember needs to be set to a string “Value” and the ValueMember set to a string “Key”. However, “Value” will attempt to display the Item object as a string, so to get around this, we need to override the ToString method of the Item object to display the property of that class. It’s easiest to understand this by seeing a sample.

 

 

private void Form1_Load(object sender, EventArgs e)

{

  //Create a Generic Dictionary.

  Dictionary<int,Item> Items = new Dictionary<int,Item>();

 

  //Load the dictionary

  Items.Add(1, new Item(“FirstItem”, 1));

  Items.Add(2, new Item(“SecondItem”, 2));

  Items.Add(3, new Item(“ThirdItem”, 3));

  Items.Add(4, new Item(“FourthItem”, 4));

 

  //Bind the generic dictionary

  comboBox1.DataSource = new BindingSource(Items, null);

 

  //For this to work, the Item.cs class needs to

  //override the ToString() method.

  comboBox1.DisplayMember = “Value”;

  comboBox1.ValueMember = “Key”;

} 

 

 

class Item

    {

        private string _itemName;

        private int _itemId;

 

        //constructor

        public Item(string strItemName, int itemId)

        {

            this._itemName = strItemName;

            this._itemId = itemId;

        }

 

        public string ItemName

        {

            get{ return _itemName; }

        }

 

 

        public int ItemId

        {

            get{ return _itemId; }

        }

 

        //Override ToString to the itemName property.

        public override string ToString()

        {

            return _itemName;

        }

    }

 

 

 

The compelte source code for this demo can be downloaded here.

 

Enjoy.

 

Follow

Get every new post delivered to your Inbox.