[Solved] C# How to clear Gridview data source without clearing the header, when clear button is clicked

dgvGridView1.DataSource=null

The above code line clearing all records with the headers as well. How do I clear the rows without clearing the header names in the gridview.

Solution

It is a pretty simple and straightforward answer to clear all the records in a GridView without clearing the header by using data table Clear() method.

DataTable dt = (DataTable)dgvGridView1.DataSource;
dt.Clear();
dgvGridView1.DataSource = dt;

Conclusion

Casting the Gridview datasource as a data table and clear the datatable and assign the cleared data table object to the gridview data source again will solve the problem, we hope you find them helpful.

Default image
Shivaraju M

Over 3+ years experience in IT industry, good knowledge in . Net-based Web applications, windows applications, web services, and SPAs. I have played
multiple roles related to technical delivery in multiple domains while working on over 10+ technologies. I am
currently focused on continuous improvement and agile project management.

Leave a Reply