【发布时间】:2021-11-15 21:55:59
【问题描述】:
我创建了一个这样的通用数据表,没关系:
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
}
现在字符串列都是空的,那么具体应该怎么实现呢?
【问题讨论】:
-
@JohnG 我已经阅读了很多答案,他们通常谈论一个方面。我还没有看到在一个数据网格视图中同时具有 datatable 和 comboColumn 的可行解决方案,而带有 不同项目 的 comboboxColumn 只是问题。
-
不幸的是,您没有明确说明您遇到问题的“方面”。如果一个“带有不同项目的comboboxColumn只是问题的一部分”……那么,问题的另一部分是什么? IMO,大多数人在这样做时遇到的问题是组合框有两 (2) 个
DataSources... 1) 是一个DataSource用于“COLUMN”,其中包含来自 ALL 的所有项目单独的组合框......然后,2)每个组合框都有自己的DataSource,这是“列”数据源中项目的“子集/过滤”版本。 -
我之前的链接的哪一部分丢失或无助于理解如何在同一个组合框列中实现不同的值?
-
@JohnG 仍然感谢您的回答。我之前的困惑是结合 datatable 和 comboboxcolumn,因为不同的行有自己的数据源,我实际上使用字典在我的代码中实现它(看起来不错,但它是 comboboxColumn 需求的一部分,所以我提到它)。现在我知道我的问题是在 datagridview 中添加两个新列,只需删除它们并将 AutoGenerateColumns 恢复为 true。
标签: c# winforms datatable datagridview datagridcomboboxcolumn