3

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.

4

3 回答 3

5

使用Keys.ToString(),您正在创建一个表示 Keys 集合的字符串,而不是获取键列表。这将返回:

System.Collections.Generic.Dictionary'2+KeyCollection[System.String,System.String]

DisplayMember 是 DataSource 中应显示在 ComboBox 中的每个项目的属性名称 - 这应该是"Value"

尝试这个:

Dictionary<string, string> CountryList=new Dictionary<string, string>();

DataGridViewComboBoxColumn buildCountries = new DataGridViewComboBoxColumn();
buildCountries.HeaderText = "List of Countries";
buildCountries.DataSource = CountryList.ToArray();
buildCountries.ValueMember = "Key";
buildCountries.DisplayMember = "Value";

CountryList.ToArray()会给你一个KeyValuePair<string, string>s 数组,它确实实现了 IList。

如果要获取所选国家/地区代码,请使用buildCountries.SelectedValue.

于 2012-11-29T21:40:29.217 回答
4

我不是 100% 肯定的,但我认为您将无法按照您尝试的方式完成此操作。我知道这可能被认为是重型火炮,但您可以从中创建一个DataTable并对其Dictionary进行操作DataBinding

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);
于 2012-11-29T21:59:31.157 回答
1

您可以使用以下内容将字典设置为 DataGridViewComboBoxColumn 的数据源

 buildCountries .DisplayMember = "Key";
 buildCountries .ValueMember = "Value";
 buildCountries .DataSource = new BindingSource(CountryList, null);
于 2017-07-25T01:33:43.430 回答