Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add New Row in datagridview which is bound to the datasource [duplicate]

I have a datagridview that is bound to a datasource. I have to add a new row in datagridview when I click Edit button or New button.I tried some code but its giving me error, code is given below

DataGridView grdview = new DataGridView();
grdview.Rows.Add();
grdview.Rows[grdview.Rows.Count - 1].Cells[0].Selected = true;
grdview.BeginEdit(false);

I also tried typecasting of datasource to datatable but no solution.

like image 641
Amit Kumar Avatar asked Sep 20 '13 10:09

Amit Kumar


3 Answers

It seems that 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.

If you are binding a List

//Assume Student list is bound as Dtaasource
List<Student> student = new List<Student>();

//Add a new student object to the list
student .Add(new Student());

//Reset the Datasource
dataGridView1.DataSource = null;
dataGridView1.DataSource = student;

If you are binding DataTable

DataTable table = new DataTable();

 DataRow newRow = table.NewRow();

// Add the row to the rows collection.
table.Rows.Add(newRow);
like image 116
Kurubaran Avatar answered Nov 08 '22 03:11

Kurubaran


No, if the DataGridView is data bound to some data source then you cannot add new rows/columns. You will have to create a new data set (DataTable or whatever) with the required columns and then re-bind the DataGridView to that.

I hope this helps.

like image 7
MoonKnight Avatar answered Nov 08 '22 03:11

MoonKnight


Bind to a BindingSource instead and you will preserve NewRow

like image 6
Mauro Sampietro Avatar answered Nov 08 '22 04:11

Mauro Sampietro