C# 在单击按钮时添加datagridview单元格会出现错误“;集合已属于..”;
我正在向表单动态添加datagridview。加载表单后,如果用户想要添加新行,我有一个按钮,用户可以使用该按钮添加一行。在此按钮上,单击我正在尝试添加DataGridViewComboxCell:C# 在单击按钮时添加datagridview单元格会出现错误“;集合已属于..”;,c#,winforms,datagridview,datagridviewcomboboxcell,C#,Winforms,Datagridview,Datagridviewcomboboxcell,我正在向表单动态添加datagridview。加载表单后,如果用户想要添加新行,我有一个按钮,用户可以使用该按钮添加一行。在此按钮上,单击我正在尝试添加DataGridViewComboxCell: DataGridViewRow dtRow = new DataGridViewRow(); dgv1.Rows.Add(dtRow); int RowIndex = dgv1.Rows.IndexOf(dtRow); int TotalRowsvailable = NPDESconfigModel
DataGridViewRow dtRow = new DataGridViewRow();
dgv1.Rows.Add(dtRow);
int RowIndex = dgv1.Rows.IndexOf(dtRow);
int TotalRowsvailable = NPDESconfigModel.Count; // rows in database
if (RowIndex >= TotalRowsvailable) // to see if this is the new row
{
List<string> a = (from p in y
select p.Point_Name).ToList();
DataGridViewComboBoxCell cbcell = new DataGridViewComboBoxCell();
cbcell.DataSource = a;
cbcell.DisplayMemeber = "Point_Name";
dgv1.Rows[RowIndex].Cells.Add(cbcell);
}
DataGridViewRow dtRow=新建DataGridViewRow();
dgv1.Rows.Add(dtRow);
int RowIndex=dgv1.Rows.IndexOf(dtRow);
int totalRowsAvailable=NPDESconfigModel.Count;//数据库中的行
if(RowIndex>=TotalRowsvailable)//查看这是否是新行
{
列表a=(从y中的p开始)
选择p.Point_Name).ToList();
DataGridViewComboBoxCell cbcell=新DataGridViewComboxCell();
cbcell.DataSource=a;
cbcell.displaymeber=“点名称”;
dgv1.Rows[RowIndex].Cells.Add(cbcell);
}
代码最后一行的例外情况如下。
集合已属于DataGridView控件。这次手术
不再有效
我不知道这是什么意思
异常发生后,表单将加载新行和空单元格 您应该将新单元格放入现有单元格,而不是单元格集合的末尾 也许是这样:
dgv1.Rows[RowIndex].Cells[yourComboboxColumnIndex] = cbcell;
错误消息表示,只要行不是DataGridview的一部分,就只能将其添加到行的Cells集合中。您可以在代码中创建DataGridViewRow,并向其添加适当数量的适当单元格。然后可以将其添加到DGV;但最终所有行都必须有相同数量的单元格。非常感谢,@TaW