Harvey
Harvey

Reputation: 389

How to empty a datagridview?

I don't know what is the syntax for emptying a datagridview. Please help me here is my code.

if (cboProduct.SelectedIndex != -1)
    load_variant();
else
    //empty the datagridview
    cboProduct.SelectedIndex = -1;

Upvotes: 10

Views: 60772

Answers (9)

Anoopkumar
Anoopkumar

Reputation: 106

Setting the DataSource to null alone didn’t work for me, but combining it with a call to Refresh resolved the issue.

// Clear the DataGridView
dgv.DataSource = null;

// Refresh the control to ensure it updates visually
dgv.Refresh();

Upvotes: 0

phanvugiap
phanvugiap

Reputation: 346

if (dgView.DataSource == null) return; ((DataTable)dgView.DataSource).Rows.Clear(); ((DataTable)dgView.DataSource).Columns.Clear();

I used this one to clean datagrid view on my window application.

dgView.DataSource = null is not working for me

Upvotes: 1

JayByte
JayByte

Reputation: 74

Setting the data source to null will also reset all formatting of the DataGridView. You can preserve the formatting by creating an empty DataTable and setting that as the source.

For example:

// Create an empty datatable
DataTable empty = new DataTable();
empty.Columns.Add("Name", typeof(string));
empty.Columns.Add("Color", typeof(myEnum));
empty.Columns.Add("Count", typeof(int));
...

// Clear datagridview
dgv.DataSource = empty;

Upvotes: 0

Jack
Jack

Reputation: 1

Try this:

int nn = yourgridview.Rows.Count;
for (int i=nn; i>1; i--)
{ 
    {
        yourgridview.Rows.RemoveAt(i-2);
    }
}

Upvotes: -1

Damith
Damith

Reputation: 63065

set datasource as null

dataGridView1.DataSource = null;

Or

dataGridView1.Rows.Clear()

OR

while (dataGridView1.Rows.Count > 0)
{
    dataGridView1.Rows.RemoveAt(0);
}

Upvotes: 38

Soner Gönül
Soner Gönül

Reputation: 98750

Just set DataGridView.DataSource property to null

Gets or sets the data source that the DataGridView is displaying data for.

DataGridView1.DataSource = null;

As an alternative (not exactly what .DataSource = null does)

DataTable dt = (DataTable)DataGridView1.DataSource;
if(dt != null)
    dt.Clear();

Upvotes: 3

Freelancer
Freelancer

Reputation: 9074

Approach 1:

datagridview1.DataSourse=null;

Approach2:

DataView DV = (DataView)this.SqlDataSource1.Select(DataSourceSelectArguments.Empty);
DV.Table.Clear();

Approach 3:

datagridview1.DataSource = ""

Approach 4:

datagridview1.Dispose();//Clears gridview with all its properties

Approach 5:

Using Javascript:

document.getElementById("datagridview1").outerHTML = "";

Hope Its Helpful.

Upvotes: 1

Maryam Arshi
Maryam Arshi

Reputation: 2024

You can set its DataSource to null :

dataGridView.DataSource = null;

Upvotes: 1

Habib
Habib

Reputation: 223247

syntax for emptying a datagridview

Just assign null to its DataSource property.

yourGridView.DataSource = null;

Upvotes: 6

Related Questions