How can I add a row to a datagridview control if it is bounded to a datasource (datatable) ? Thanks!
DataGridView grdview = new DataGridView(); grdview. Rows. Add(); grdview.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With