How can I clear rows in DataGridView with C#?

c#, datagridview

Solution

I also had similiar problem when I try to clear DataSource of a DataGridView after I had binded it to a DataTable with:

DataTable DT = ... ; // fill it
datagridview1.DataSource = DT;

when I try to clear it's rows later with the following code:

datagridview1.DataSource = null

I get this error:

ERROR: Object reference not set to an instance of an object

This object reference ERROR problem already solved in here. But I managed to solve my own problem (clearing DataGridView rows) with this code:

DataTable DT = (DataTable)datagridview1.DataSource;
if (DT != null) 
    DT.Clear();

I know that this question was asked a very long time ago, but I hope my solution would solve someone problems.

Problem

Following Error in this line. ``` datagridview1.Rows.Clear() ``` but this line gives error: Cannot clear this list.

Original source

Related problems