C# 使用addrange添加具有混合列类型的datagridviewrow
我有一个datagridview,它由数据库中的数据填充,最后两列是一个组合框和一个按钮 为了防止闪烁,我使用Rows.AddRange一次添加所有行,整个过程都在backgroundworker中 我的问题是如何将这些值添加到下拉框中。这些项目只是一个stings列表,因此无需对其进行数据源化C# 使用addrange添加具有混合列类型的datagridviewrow,c#,winforms,datagridviewcomboboxcell,C#,Winforms,Datagridviewcomboboxcell,我有一个datagridview,它由数据库中的数据填充,最后两列是一个组合框和一个按钮 为了防止闪烁,我使用Rows.AddRange一次添加所有行,整个过程都在backgroundworker中 我的问题是如何将这些值添加到下拉框中。这些项目只是一个stings列表,因此无需对其进行数据源化 DataTable dt = db.fill(query, dbpars); DataGridViewComboBoxCell cbox = new DataGridViewComboBoxCell()
DataTable dt = db.fill(query, dbpars);
DataGridViewComboBoxCell cbox = new DataGridViewComboBoxCell();
cbox.Items.Add("--Please Select--");
cbox.Items.Add("Generate");
cbox.Items.Add("Ignore");
List<DataGridViewRow> rowList = new List<DataGridViewRow>();
foreach (DataRow row in dt.Rows)
{
DataGridViewRow drow = new DataGridViewRow();
drow.CreateCells(dgvClientWork);
drow.Cells[0].Value = row[0];
drow.Cells[1].Value = row[1];
drow.Cells[2].Value = row[2];
drow.Cells[3].Value = row[3];
drow.Cells[4].Value = row[4];
drow.Cells[5].Value = row[5];
//((DataGridViewComboBoxColumn)dgvClientWork.Columns[6]).Items.Add("2");
//var td = new DataGridViewComboBoxCell();
//drow.Cells[6] = td;
//((DataGridViewComboBoxCell) drow.Cells[6]).Items.Add("WFT");
DataGridViewComboBoxCell td = (DataGridViewComboBoxCell)dgvClientWork.Rows[0].Cells[6];
td.Items.Add("--Please Select--");
td.Items.Add("Generate");
td.Items.Add("Ignore");
//td.Items.AddRange(new object[]{"--Please Select--", "Generate", "Ignore"});
//var t = (DataGridViewComboBoxCell)cbox.Clone();
//drow.Cells.Add(t);
//drow.Cells[6] = t;
//drow.Cells[6].Value = "--Please Select--";
/*drow.Cells[7].Value = btn;*/
rowList.Add(drow);
}
Action action = () => dgvClientWork.Rows.AddRange(rowList.ToArray());
dgvClientWork.Invoke(action);
正如您所看到的,我尝试了几种方法,但组合框始终为空。如果我正确复制了您的问题,如果您检查dgv中的最后一行,则该下拉列表将包含您添加的项目的倍数 若要修复,请更改此代码行:
DataGridViewComboBoxCell td = (DataGridViewComboBoxCell)dgvClientWork.Rows[0].Cells[6];
为此:
DataGridViewComboBoxCell td = (DataGridViewComboBoxCell)drow.Cells[6];
编辑:如果希望单元格默认,只需添加
td.Value = "--Please Select--";
然后为我工作
编辑:另一方面,当您创建DGV并添加列时,我会创建ComboBoxColumn并将其数据源设置为代码中设置的相同字符串的列表。这样,用户新添加的任何行也将具有相同的combobox源。从现在起,任何新行都将有空的组合框。为了防止闪烁,我使用rows.AddRange-您也可以使用。@Sinatr谢谢您的帮助,遗憾的是,这并不能解决我遇到的问题:这就是为什么我不为您发布答案;也许您没有添加行?您在表单构造函数中的何处执行此代码?@Ohbowise在后台工作程序中,该工作程序在表单加载时运行