namco
namco

Reputation: 6338

C# DataGridView data-bound error with Grid.Rows.Add method

i have a DataGridView on the Form. I select some data from database and load them to datatable and after that i make reference this datatable to grid's datasorurce as below.

string sql = "";
sql = "SELECT id,name,surname,code FROM t_persons";
DataTable dt = new DataTable();
...
adapter.Fill(dt);
grid.DataSource = dt;

and after that i want to add new row to this grid with grid.Rows.Add() method. But every time it gives an error Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound.
So whatis the problem and how can i solve it.

Upvotes: 0

Views: 1446

Answers (2)

Vikram Jain
Vikram Jain

Reputation: 5588

Please you can add row directly to datatable and it's effect on gridview because it's bind to datatable.

Upvotes: 1

Vale
Vale

Reputation: 3298

You should add row to the DataTable, not to the DataGridView. That is what the exception is saying. Try:

DataRow newRow = dt.NewRow();
dt.Rows.Add(newRow);

Upvotes: 2

Related Questions