Clear Datagridview Rows

Clear Datagridview Rows

Added by Nasir Mahmood updated on Friday, November 17, 2017

Problem:

While working on Datagridview we have to clear all rows after performing some operation. In this snippet i am combining different ways to achieve this.

Setup:

For this code snippet we use following code to generate dummy data.

DataTable dataTable = new DataTable();
dataTable.Columns.Add("ID");
dataTable.Columns.Add("Name");
dataTable.Columns.Add("Address");

for (int i = 1; i < 10; i++)
{
    dataTable.Rows.Add(i, "Name " + i, "Address 1");
}

dataGridView1.DataSource = dataTable;
				

Using DataSource null:

First method to achieve this task is to set DataSource property to null. Drawback of this solution is we also lost columns information on datagridview.

dataGridView1.DataSource = null;				
				

Using Loop:

Another method is to use loop which clear datagridview rows one by one.

while (dataGridView1.Rows.Count > 1)
{
    if (!dataGridView1.Rows[0].IsNewRow)
        dataGridView1.Rows.RemoveAt(0);
    else
        break;
}
				

Using DataSource Clear:

Another method is to use Datasource.Clear() method which will clear all data associate with datasource and retain metadata.

if datasource is DataTable

((DataTable)dataGridView1.DataSource).Clear();
OR
((DataTable)dataGridView1.DataSource).Rows.Clear();
				

if datasource is DataSet

((DataSet)dataGridView1.DataSource).Tables[0].Clear();
OR
((DataSet)dataGridView1.DataSource).Tables[0].Rows.Clear();
				

We can also clear Datasource which is bound to datagridview as.

dataTable.Clear();
OR
dataTable.Rows.Clear();
				

About

29 Tutorials
25 Snippets
6 Products

More

Contact Us

Contact us

Stay Connected