Search code examples
c#winformsdatagridviewdatagridviewcomboboxcell

Adding a datagridview cell on button click brings up error "Collection already belongs.."


I am dynamically adding a datagridview to a form. After the form is loaded, if the user wants to add a new row, I have a button with which the use can add one. On this button click I am trying to add a 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);
}

The exception I get on the last line of the code is as below. Collection already belongs to a DataGridView control. This operation is no longer valid.

Not sure what it means.

After the exception the forms loads with a new row and empty cell.


Solution

  • You should put the new Cell into an exising Cell, not to the end the Cells collection.

    Maybe like this:

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

    The error message means that you can only add to the Cells collection of a Row as long as it is not part of a DataGridview. You can create a DataGridViewRow in code and add a suitable number of suitable Cells to it. Then you can add it to a DGV; but eventually all rows must have the same number of Cells..