Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add new row to datagridview?

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?

like image 992
Bodi Avatar asked Mar 07 '12 20:03

Bodi


2 Answers

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

like image 60
casperOne Avatar answered Nov 07 '22 10:11

casperOne


The short answer is, you don't.

When you set your DataSource to null, you've broken the link between your DataGridView and your data source, so its data won't be persisted. You can't add a row to a bound DataGridView because it's supposed to represent the state of the underlying DataSource; you're effectively asking .net to make your table out of sync with its backing store, defeating the purpose of databinding in the first place.

If you want to add a row to the backing store, you should be adding a row in the DataSource, not in your DataGridView.

like image 1
Jim Dagg Avatar answered Nov 07 '22 11:11

Jim Dagg