【问题标题】:Adding a datagridview cell on button click brings up error "Collection already belongs.."在按钮单击时添加 datagridview 单元格会出现错误“集合已属于..”
【发布时间】:2015-07-24 14:57:59
【问题描述】:

我正在动态地将数据网格视图添加到表单中。加载表单后,如果用户想要添加新行,我有一个按钮,用户可以使用该按钮添加新行。在此按钮上单击我正在尝试添加一个 DataGridViewComboBoxCell:

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);
}

我在代码的最后一行得到的异常如下。 集合已属于 DataGridView 控件。这个操作 不再有效。

不知道是什么意思。

出现异常后,表单会加载新行和空单元格。

【问题讨论】:

    标签: c# winforms datagridview datagridviewcomboboxcell


    【解决方案1】:

    您应该将新的 Cell 放入现有的 Cell 中,而不是放入 Cells 集合的末尾。

    可能是这样的:

     dgv1.Rows[RowIndex].Cells[yourComboboxColumnIndex] = cbcell;
    

    错误消息意味着您只能添加到 Row 的 Cells 集合中,只要它不是 DataGridview 的一部分。您可以在代码中创建 DataGridViewRow 并向其中添加合适数量的合适单元格。然后您可以将其添加到 DGV;但最终所有行必须具有相同数量的单元格..

    【讨论】:

      猜你喜欢
      • 2016-04-21
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 2013-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-25
      相关资源
      最近更新 更多