I have DataGridView filled with data from datasource (SQL). Now I want to a add new row, but I can't, because new data can't be added to bounded DataGridView…
I was trying to :
dataGridView1.Source = null;
dataGridView1.Rows.Add("1");
but it clears my previous data in table. How to do it, to add new row without deleting previous data?
Best Answer
When you set the
DataSource
property tonull
, you are essentially removing all data from theDataGridView
(since it doesn't know what to bind to anymore).You have two options here. The first is to update the underlying data source. Let's assume that it's a
DataTable
. In this case, you'd do something like:And then the
DataGridView
will pick up on the changes (note that if you are not binding to something that doesn't implement theINotifyCollectionChanged
interface, you'll have to call theResetBindings
method to get the grid to refresh).The other option is to let the
DataGridView
manage the rows. You can do this by manually adding each item using theAdd
method on theDataGridViewRowCollection
returned by theRows
property:I wouldn't say the second solution is optimal, but it will work.
Finally, assuming you are binding to a
DataTable
(or some other materialization of the data from an underlying data source), this doesn't do anything about to updating underlying data source (that would be a separate question).