Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically add a row to a datagridview when it is data-bound?

How can I add a row to a datagridview control if it is bounded to a datasource (datatable) ? Thanks!

like image 821
NickSharp Avatar asked Aug 08 '13 11:08

NickSharp


People also ask

How to add row to DataGridView in c# when data binding?

DataGridView grdview = new DataGridView(); grdview. Rows. Add(); grdview.

How do you fix Rows Cannot be programmatically added to the DataGridView Rows collection when the control is data bound?

You have two solutions: Either you strip off the data binding and do the boilerplate code yourself. Or you add a new record to the datasource and refresh the gridview => it will update itself with the new row.

How to add new row in bound DataGridView in vb net?

If you loaded the DataGridView using a DataTable (or a DataTable from a DataSet) then when you need to add a new row, cast the DataGridView. DataSource to a DataTable then use Rows. Add. In the example below the first DataColumn in the DataTable is the primary key and hidden in the DataGridView.


1 Answers

Add a row to the datatable, the datagridview will update automatically:

DataTable dt = myDataGridView.DataSource as DataTable;
//Create the new row
DataRow row = dt.NewRow();

//Populate the row with data

//Add the row to data table
dt.Rows.Add(row);
like image 142
Avi Turner Avatar answered Sep 25 '22 06:09

Avi Turner