Share via


How to clear datagridview all rows?

Question

Saturday, December 15, 2007 5:30 AM

Hi to all,

 

I have a datagridview on a form. I required it to clear all rows of datagridview on button click event.

 

I tried the syntax ::

        dataGridView1.Rows.Clear();

But that syntax threws an exception "Cannot Clear The List".

 

Currently i am using the syntax ::

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

 

Here, I want to know that is the method mentioned later is the appropriate to clear the datagridview rows or is their any other method to clear the datagridview rows.

 

Thanks

Sandeep Soni

All replies (8)

Saturday, December 15, 2007 9:14 AM âś…Answered | 4 votes

Hi,

 

Try this :

 

Code Block

Code Changed :

dataGridView1.Rows.Clear()

or

dt.Rows.Clear() // If dgv is bound to datatable

dataGridView1.DataBind();

 

 

or

 

Use this code to check if you are bound to a data source :

 

Code Block

if (this.dataGridView1.DataSource != null)
{
     this.dataGridView1.DataSource = null;
}
else
{
    this.dataGridView1.Rows.Clear();
}

 

 

 

HTH,
Suprotim Agarwal

http://www.dotnetcurry.com


Saturday, December 15, 2007 8:52 AM

 

if tou use datasource to fill the grid use:

 

dataGridView1.DataSource=null;

dataGridView1.refresh();

 

if you fill the grid programitalty use:

 

dataGridView1.Rows.Clear();

 

 


Saturday, December 15, 2007 11:22 AM

Here I check that the datatable is not directlty accessibe throught datasource property of datagridview.

 

"dataGridView1.DataSource.Table.Rows.Clear();" in that part i could not find any table property after the data source property of datagridview.

 

 

 


Saturday, December 15, 2007 2:55 PM

Hi,

 

That was a typo. I have changed the code. Kindly have a look at it again.

 

 

HTH,
Suprotim Agarwal

http://www.dotnetcurry.com

 


Monday, December 17, 2007 8:45 AM

Thanks Suprotim for you helpful suggestions.


Friday, November 11, 2011 4:20 AM

You cant clear the datagrid by just making the datasource into nothing..but you should clear your dt or data table like....dt.clear() the it works.


Wednesday, May 30, 2012 10:43 AM

Both of your codes ain't working....2nd one gives error,

"Unable to cast object of type 'System.Data.DataView' to type 'System.Data.DataTable'."


Wednesday, March 16, 2016 3:39 AM

Thanks a million for your suggestion.....