Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I clear rows in DataGridView with C#?

Following Error in this line.

datagridview1.Rows.Clear()

but this line gives error:

Cannot clear this list.

like image 854
HeavenGod Avatar asked May 31 '11 07:05

HeavenGod


People also ask

How to Clear DataGridView Rows and columns in c#?

dataGridView1. Columns. Clear(); with the same results - number of columns was changed.

How to Clear DataGridView in c# winform?

If your DataGridView is bounded, "dataGridView1. DataSource = null" is sufficient to clear it. If you want to Refresh it after a new fill, set the DataSource to null and restore it to what it was before, i.e. DataTable or BindingSource.

How to Clear DataGridView in asp net?

To clear GridView assign null to the GridView datasource.

How do I delete a row from GridView in Windows app?

When the Delete Button is clicked, the DataGridView CellContentClick event handler is executed. If the ColumnIndex is 3 i.e. the Delete Button is clicked, then a Confirmation MessageBox us show and if the User clicks Yes button the Row will be deleted (removed) from DataGridView and Database Table.


4 Answers

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.

like image 60
Aryo Avatar answered Sep 28 '22 15:09

Aryo


Is your DataGridView bound to a DataSource, i think thats why its not allowing you to clear it since its bound to an underlying DataTable or List.

you could try setting the DataSource Property to null

datagridview1.DataSource = null; for clearing

like image 28
V4Vendetta Avatar answered Sep 28 '22 13:09

V4Vendetta


private void button_Limpar_Click(object sender, EventArgs e)
{
    DataTable DT = (DataTable)dataGridView_Cidade.DataSource;
    if (DT != null)
        DT.Clear();
}
#endregion
like image 37
elson Avatar answered Sep 28 '22 14:09

elson


Simply add this line at beginning of your event:

dgv_nameOfGridView.DataSource=false;

Now every time you click it will erase the dgv..

like image 39
Gabrijel Gale Baban Avatar answered Sep 28 '22 15:09

Gabrijel Gale Baban