Wednesday, 14 August 2013

Data binding a WinForms ComboBox control with a dictionary

Sometime when working with winforms we have to load items to a combo box and the starting value can be some information display.



here is how to do that,
all you have to do is just drop a combo box in to ms form and then code like the following

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            loadComboElements();
        }

        private void loadComboElements()
        {
            Dictionary<int, string> keyValueDic = new Dictionary<int, string>();
            keyValueDic.Add(-1, "Please select an item");
            keyValueDic.Add(1, "sample item 1");
            keyValueDic.Add(2, "Sample item 2");

            comboBox1.DataSource = keyValueDic.ToList();
            comboBox1.DisplayMember = "VALUE";
            comboBox1.ValueMember = "Key";
        }
    }
}


  • Remember you have to use "ToList()" on dictionary  and also, use "Key" and "Value" to identify the display member and value member.





No comments:

Post a Comment