Rows cannot be programmatically added to the datagridview's row collection when the control is data-bound
It appears as though you are using the DataSource property of the DataGridView. When this property is used to bind to data you cannot explicitly add rows directly to the DataGridView. You must instead add rows directy to your data source.
For example if your data source is a DataTable, using the DataTable that is assigned to the DataSource property (untested):
private void AddARow(DataTable table)
{
// Use the NewRow method to create a DataRow with
// the table's schema.
DataRow newRow = table.NewRow();
// Add the row to the rows collection.
table.Rows.Add(newRow);
}
You can get the DataGridView
's DataSource
and cast it as a DataTable
.
Then add a new DataRow
and set the fields' values.
Add the new row to the DataTable
and Accept the changes.
In C# it would be something like this:
DataTable dataTable = (DataTable)dataGridView.DataSource;
DataRow drToAdd = dataTable.NewRow();
drToAdd["Field1"] = "Value1";
drToAdd["Field2"] = "Value2";
dataTable.Rows.Add(drToAdd);
dataTable.AcceptChanges();