How to bind a Dictionary to DataSource of DataGridView

12,337

Solution 1

Check out the docs for the DataSource property. It only handles specific types (IList, IListSource etc.). So you cannot bind it to an IDictionary. So, this will work:

List<KeyValuePair<string, string>> d = new List<KeyValuePair<string, string>>();
d.Add(new KeyValuePair<string, string>("1", "2323"));
d.Add(new KeyValuePair<string, string>("2", "1112323"));

DataGridView v = new DataGridView();
v.DataSource = d;

Solution 2

If you really want to bind to dictionary you can try this using linq where foreach KeyValuePair you will create a Anonymous Type and convert to a list like so:

Assuming your datagridview is called dataGridView1:

Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("1", "test1");
d.Add("2", "test2");
dataGridView1.DataSource = (from entry in d
                            orderby entry.Key
                            select new{entry.Key,entry.Value}).ToList();

Solution 3

Old question but since I just stumbled across it, maybe somebody else will too. Dictionaries know how to make themselves into lists, so this will do it:

myDataGrid.DataSource = myDictionary.ToList();
Share:
12,337
Emetrop
Author by

Emetrop

WordPress developer from the Czech Republic.

Updated on July 28, 2022

Comments

  • Emetrop
    Emetrop over 1 year

    I think that question is clear. I have a Dictionary instance and I want to bind it like DataSource of a DataGridView instance. Actually I can bind it straight this way:

    Dictionary<string,string> d = new Dictionary<string,string>();
    d.Add("1","test1");
    d.Add("2","test2");
    DataGridView v = new DataGridView();
    
    v.DataSource = d;
    

    But without any results.

  • Milana
    Milana about 3 years
    Worth mentioning you should add using System.Linq at the top of the page
  • Kishori
    Kishori almost 3 years
    Thanks a lot. This is perfect answer.