Pieter888 Pieter888 - 2 months ago 4x
C# Question

How to empty the cells of a DataGridView in C#?

I've found questions similar on SO already, all over the net actually. Though I haven't found a working answer yet.

So I'm working in a windows form application using Visual studio 2008. Language is C#

I have a DataGridView that is not bound to a DataSource.


MyDataGridView.DataSource = null;

wont work...

I've also tried


But this removes all my custom made rows.

So I'm now looking for a way to just empty the contents of all cells (not including header cells). So it shouldn't affect anything else but the contents of the cells itself.


I just figured out how to do it myself, I simply loop trough the table, clearing every cell I encounter.

note: "dgUsers" is the name of my DataGridView

for (int i = 0; i < dgUsers.Columns.Count ;i++ )
          for (int j = 0; j < dgUsers.Rows.Count; j++)
               dgUsers.Rows[j].Cells[i].Value = "";

I bet there is a better way to do this and this might look a bit sloppy but it does the job. Yet I'd like to hear a better solution that clears the data.