C# – How to add new row to datagridview

cdatagridview

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 to null, you are essentially removing all data from the DataGridView (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:

DataTable dt = dataGridView1.Source as DataTable;
dt.Rows.Add(new object[] { ... });

And then the DataGridView will pick up on the changes (note that if you are not binding to something that doesn't implement the INotifyCollectionChanged interface, you'll have to call the ResetBindings 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 the Add method on the DataGridViewRowCollection returned by the Rows property:

foreach (var item in source)
{
    dataGridView1.Rows.Add("1", "2", "3", ...);
}

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).

Related Topic