我有一本字典,其键为三个字母的国家/地区代码,其值为国家/地区名称。
Dictionary<string, string> CountryList=new Dictionary<string, string>();
我还有一个 DataGridView 和一个 DataTable。我想要做的是为我的 DataTable 列中显示国家/地区信息的某些列创建一个 DataGridViewComboBoxColumn。因此,例如,我的数据表中的一列称为Country
,我希望该列有一个下拉组合框,显示国家/地区名称,选择该组合框后,将使用字典中的键(三个字母代码)填充数据表中的单元格。但是,我完全不知道如何做到这一点。我是否必须将 DataSource 设置为键,将 DisplayMember 设置为值?我尝试了一下,并得到一个错误:
DataGridViewComboBoxColumn buildCountries = new DataGridViewComboBoxColumn();
buildCountries.HeaderText = "List of Countries";
buildCountries.DataSource = CountryList.Keys.ToString();
buildCountries.DisplayMember = CountryList.Values.ToString();
复杂数据绑定接受 IList 或 IListSource 作为数据源
我不知道该怎么做。
With Keys.ToString()
,您正在创建一个代表 Keys 集合的 String,而不是获取键列表。这将返回:
System.Collections.Generic.Dictionary'2+KeyCollection[System.String,System.String]
DisplayMember 是数据源中每个项目的属性名称,应显示在组合框中 - 这可能应该是"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
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)