Ama*_*nda 3 c# ado.net winforms
我有一本字典,其键为三个字母的国家/地区代码,其值为国家/地区名称。
Dictionary<string, string> CountryList=new Dictionary<string, string>();
Run Code Online (Sandbox Code Playgroud)
我还有一个 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();
Run Code Online (Sandbox Code Playgroud)
复杂数据绑定接受 IList 或 IListSource 作为数据源
我不知道该怎么做。
使用Keys.ToString()
,您将创建一个代表 Keys 集合的 String,而不是获取键列表。这将返回:
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";
Run Code Online (Sandbox Code Playgroud)
CountryList.ToArray()
会给你一个KeyValuePair<string, string>
s 数组,它确实实现了 IList。
如果您想获取所选国家/地区代码,请使用buildCountries.SelectedValue
。
归档时间: |
|
查看次数: |
11128 次 |
最近记录: |