c# - 使用字典键和值填充 DataGridViewComboBoxColumn

标签 c# winforms ado.net

我有一本字典,它的键是三个字母的国家代码,值是国家的名称。

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

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

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

我不确定该怎么做。

最佳答案

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 .

关于c# - 使用字典键和值填充 DataGridViewComboBoxColumn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13635109/

相关文章:

c# - 对象类型变量如何接受类类型实例

c# - 如何使用 MvcContrib 的 XmlResult 生成带有属性而不是节点的 XML?

c# - C# Windows 窗体应用程序中的全局变量方法? (公共(public)静态类 GlobalData 是最好的)

C#、winform - NumericUpDown 最大限制未在 KeyPress 上验证?

c# - 使用 C# 中对象的值写入文件

C#:数据类型与类型相同吗?

c# - 接收命令时通过 TCP 发送字符串

.net - 从 WCF/ADO.NET 数据服务中的请求正文接收参数

c# - 为什么我在这里得到 "Connection property has not been initialized"?

sql-server - 存储过程执行需要时间