0
votes

I wanted to bind a dictionary to a datagridview. Unfortunately Dictionary does not implement the required interface, so instead a created a List>.

Essentially I want this to be bound to a datagridview with datagridviewcomboboxcolumns. With column 1 holding the Key and column 2 holding the value.

I've tried loads of variations, but I can't seem to get this right. I've tried binding to the columns, to individual cells, and to the datagridview itself. Does anybody know how to do this?

EDIT: To clarify it's not binding to the object that's the problem. It seems to binding to the List okay, for example, if I have 4 items in the List, then 4 rows are added, however the values are blank. This is the example code:

additionalMetadata1.dataGridView1.DataSource = animal.AdditionalMetaData;

        foreach (DataGridViewRow row in additionalMetadata1.dataGridView1.Rows)
        {
            DataGridViewCustomComboCell cell = row.Cells[0] as DataGridViewCustomComboCell;
            cell.DataSource = animal.AdditionalMetaData;

            ((DataGridViewCustomComboColumn)additionalMetadata1.dataGridView1.Columns[0]).DisplayMember = "Key";

            ((DataGridViewCustomComboColumn)additionalMetadata1.dataGridView1.Columns[0]).ValueMember = "Key";

            ((DataGridViewCustomComboColumn)additionalMetadata1.dataGridView1.Columns[0]).DataPropertyName = "Key";
         }

Thanks.

2
possible duplicate of DataGridView bound to a Dictionarydrharris

2 Answers

5
votes

You could use your Dictionary with the following Linq:

 dataGridView.DataSource =  (from d in dictionary
                             orderby d.Value
                             select new
                              {
                               d.Key,
                               d.Value
                             }).ToList();

This will create an anonymous object that will hold your Key and Value as properties. Be aware that the dictionary is by default not in a particular order.

0
votes

Try like this

dataGridView1.ColumnCount = 2;
foreach (KeyValuePair<string, string> kvp in dict) {
    string[] arow = new string[] { kvp.Key, kvp.Value };
    dataGridView1.Rows.Add(arow);
}

or

dataGridView1.DataSource = dict.ToArray();

or

dataGridView1.DataSource = dict.Select((kv => new {
    myKeys = kv.Key,
    myValues = kv.Value
})).ToArray();