使用字典键和值填充DataGridViewComboBoxColumn [英] Populating a DataGridViewComboBoxColumn with dictionary keys and values

查看:120
本文介绍了使用字典键和值填充DataGridViewComboBoxColumn的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本字典,其中有一个以三个字母组成的国家/地区代码作为键,并以国家/地区名称作为其值。

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>();

我也有一个DataGridView和一个DataTable。我想为显示国家信息的DataTable列中的某些列创建一个DataGridViewComboBoxColumn。因此,例如,我在DataTable中的一列称为 Country ,我希望该列具有一个下拉组合框,以显示该列的名称。国家(地区),并且选中该国家/地区时,将使用字典中的键(三个字母的代码)填充DataTable中的单元格。但是,我对如何执行此操作完全感到困惑。我是否必须将DataSource设置为键,将DisplayMember设置为值?我试过了,但出现了错误:

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接受IList或IListSource <作为数据源/ p>

Complex DataBinding accepts as a data source either an IList or an IListSource

我不确定如何执行此操作。

I'm not sure how to go about doing this.

推荐答案

我不是100%积极,但我认为您将无法以尝试的方式实现这一目标。我知道这可能被视为重型火炮,但是您可以从词典中创建一个 DataTable 并执行 DataBinding

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);

这篇关于使用字典键和值填充DataGridViewComboBoxColumn的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆