gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:34:40 28 4
gpt4 key购买 nike

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

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com