VB.Net clear datagridview rows without the headers

datagridviewvb.netwinforms

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.

Best Answer

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

Related Topic