c# - 如何将每行具有不同组合框项的 DataTable 绑定到 DataGridView?
问题描述
我创建了一个这样的通用数据表,很好:
BindingSource bindingSource1 = new BindingSource();
bindingSource1.DataSource = CreateDataTable();
dataGridView1.DataSource = bindingSource1;
private DataTable CreateDataTable()
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("String1"));
dt.Columns.Add(new DataColumn("String2"));
DataRow dr = dt.NewRow(); dr["String1"] = "a"; dr["String2"] = "aa"; dt.Rows.Add(dr);
dr = dt.NewRow(); dr["String1"] = "b"; dr["String2"] = "bb"; dt.Rows.Add(dr);
//...
return dt;
}
但是我需要一个 comboBoxColumn,它在 datatablegrid 中的每一行都有不同的数据源,所以我参考了一些解决方案,尝试将 Columns 和 DataSource 设置为 datagridview :
dataGridView1.AutoGenerateColumns = false;
dataGridView1.Columns.Add("String1", "String1");
dataGridView1.Columns.Add("String2", "String2");
DataGridViewComboBoxColumn comboCol = new DataGridViewComboBoxColumn();
comboCol.HeaderText = comboCol.DataPropertyName = comboCol.Name= "combo1";// fixed by ConnorTJ
dataGridView1.Columns.Add(comboCol);
bindingSource1.DataSource = CreateDataTable();
dataGridView1.DataSource = bindingSource1;
Dictionary<int, List<string> > comboDic = new Dictionary<int, List<string> >() {
{ 0, new List<string>() { "1", "11", "111" } },
{ 1, new List<string>() { "2", "22", "222" } } };
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
DataGridViewComboBoxCell comboCell = (DataGridViewComboBoxCell)dataGridView1.Rows[i].Cells["combo1"];
comboCell.DataSource = comboDic[i];
//comboCell.Value = "n";//set the value out of items will throw error
}
现在字符串列是空的,那么究竟应该如何实现呢?
解决方案
你还没有设置实际的 ColumnsName
属性,你已经设置了DataPropertyName
属性
设置comboCol.Name
属性后,执行以下操作时:
var comboCol = new DataGridViewComboBoxColumn
{
HeaderText = "combo1",
DataPropertyName = "combo1",
Name = "combo1"
};
然后你可以这样做:
var comboCell = (DataGridViewComboBoxCell)dataGridView1.Rows[i].Cells[comboCol.Name];
comboCell.DataSource = comboDic[i];
comboCell.Value = "n";
补充说明:您也可以使用该comboCol.Index
属性,这将为您提供列索引。
推荐阅读
- android - android studio中的syso快捷方式?
- android - 不推荐使用 android 命令
- apache-spark - 如何使用 put 和 get 将 list[String] List[(String,Int)] 存储和检索到 mapr/hbase 表中
- c++ - 来自模块项的 QQmlComponent
- c++ - 使用 std::map 在直方图峰值附近取平均值
- php - 使用 PHP 和 MySQL 更新信息
- xcode - 如何在 ScrollView 中制作粘性页脚横幅?(Xcode)
- python - .Thumbdata3 文件提取。TypeError:需要一个类似字节的对象,而不是“str”
- javascript - 如何在我的组件中获取 JSON 承诺错误状态?角度 - 离子
- php - PHP 脚本适用于我的本地电脑,但不适用于我的服务器