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.
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);
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.
Bind to a BindingSource
instead and you will preserve NewRow
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