Question

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.

so:

MyDataGridView.DataSource = null;

wont work...

I've also tried

MyDataGridView.Rows.Clear();

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.

Was it helpful?

Solution 2

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.

OTHER TIPS

for (int i = 0; i < MyDataGridView.Columns.Count ;i++ )
  {
      for (int j = 0; j < MyDataGridView.Rows.Count; j++)
      {
           MyDataGridView.Rows[j].Cells[i].Value = DBNull.Value;
      }
  }

the code by pieter888 didnt worked for me the code i figured out was

int cnt=dataGridView1.Rows.Count;
        for (int i = 0; i < cnt; i++)
        {
            dataGridView1.Rows.Remove(dataGridView1.Rows[0]);
        } 

I believe that using LINQ you can make it cleaner, specially with implicit types:

    foreach (var cell in from DataGridViewRow row in dgv.Rows from DataGridViewCell cell 
    in row.Cells select cell){
        cell.Value = string.Empty;
     }

you can clear the entire grid by using

gridviewname.columns.clear();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top