codeGEN
codeGEN

Reputation: 714

VB.Net clear datagridview rows without the headers

I have a datagridview with columns added from the designer, the data for this grid will be selected from the database and will be directly bound to the grid. For this purpose I have DataPropertyName to the column names of the database table.

I am setting the datasource like this :

dgPayment.DataSource = myDatatable

Now I need to clear the rows of the datagridview without removing the headers of the datagridview. I tried using dgPayment.Rows.Clear(), but this prompted a error because the grid is bound & therefore the rows cannot be manually altered. I also tried setting the datasource to nothing like this :

dgPayment.DataSource = Nothing

But this removes the headers too, which doesn't need to happen because they are the column headers that I added using the designer. How can I clear only the data without clearing the headers.

Upvotes: 0

Views: 18152

Answers (3)

A G
A G

Reputation: 22587

Remove only rows from the datatable.

DataTable.Rows.Clear(). This will keep the columns intact.

Then to refresh the data -

CurrencyManager cm = ((CurrencyManager)) dataGridView1.BindingContext[dataGridView1.DataSource];
cm.Refresh();

Upvotes: 2

Sathish
Sathish

Reputation: 4487

Try like this

dataGridView1.DataSource.Rows.Clear()

Upvotes: 1

Fabio
Fabio

Reputation: 32455

If you create columns through designer, then in form constructor or in Load event handler put next line of code

dgPayment.AutoGenerateColumns = false

Then freely use dgPayment.DataSource = Nothing for removing all rows

Upvotes: 4

Related Questions