Populating a DataGridViewComboBoxColumn with dictionary keys and values

ado.net, c#, winforms

Solution

I'm not 100% positive but I think you won't be able to accomplish this the way you were trying. I know that this may be considered as heavy artillery but you could create a `DataTable` out of the `Dictionary` and do a `DataBinding` on it.

DataGridViewComboBoxColumn buildCountries = new DataGridViewComboBoxColumn();
buildCountries.HeaderText = "List of Countries";
DataTable dataTable = new DataTable();
dataTable.Columns.Add("Keys");
dataTable.Columns.Add("Values");
KeyValuePair<string, string> [] array = CountryList.ToArray();
foreach(KeyValuePair<string, string> kvp in array)
{
        dataTable.Rows.Add(kvp.Key, kvp.Value);
}
buildCountries.DataSource = dataTable;
buildCountries.DisplayMember = "Values";
buildCountries.ValueMember = "Keys";
dataGridView1.Columns.Add(buildCountries);

Problem

I have a dictionary that has as its keys a three letter country code, and as its values the name of the country. ``` Dictionary<string, string> CountryList=new Dictionary<string, string>(); ``` I also have a DataGridView and a DataTable. What I'd like to do is to create a DataGridViewComboBoxColumn for certain columns in my DataTable-columns that display country information. So, for example, one of my columns in my DataTable is called `Country`, and I'd like for that column to have a drop down combo box that displays the name of the country, and that when selected, populates the cell in the DataTable with the key from the dictionary (the three letter code). However, I'm totally stumped as to how to do this. Do I have to set the DataSource to the keys, and the DisplayMember to the values? I tried that, and got an error: ``` DataGridViewComboBoxColumn buildCountries = new DataGridViewComboBoxColumn(); buildCountries.HeaderText = "List of Countries"; buildCountries.DataSource = CountryList.Keys.ToString(); buildCountries.DisplayMember = CountryList.Values.ToString(); ``` Complex DataBinding accepts as a data source either an IList or an IListSource I'm not sure how to go about doing this.

Original source