2
votes

I have a DataGridView bounded to a SLQ Server CE database table.

I created an Add button, when the button is pressed I would like to add a new row to the DataGridView in order to allow the user to insert new data into the DataGridView.

I also would like that the data will be persisted into the bounded database once the user finishes his input in this new row.

I have tried:

dataGridView1.Rows.Add();

Inside the button click event in order to insert a new row, but I get the following error message:

Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound

Any suggestions?

2

2 Answers

3
votes

You have to add the row to the DataTable or whatever object you're using to interface between the SQL and the DataGridView (in other words the object that you set dataGridView1.DataSource equal to).

For Example:

// set DataSource
dataGridView1.DataSource = dataTable1;

// add row
dataTable1.Rows.Add();

If you don't want to control the adding yourself, you can do what @InBetween said and set dataGridView1.AllowUserToAddRows to true.

3
votes

You can allow the user to add rows by setting DataGridView.AllowUserToAddRows to true. This will allow the user to add as many new rows as he wants and edit the values of the fields.

Another option is to add a new "default" row directly to the DataGridView.DataSource (IList or IListSource object). It amounts to the same thing as letting the user add rows but it has the advantage that you can control the amount of rows added (for example the user should only be allowed to add 1 row, in which case you would set AllowUserToAddRows to false).