Clear a datagridview in C#

Asked

Viewed 15,655 times

3

I tried all this already and nothing has worked. Everyone is deleting the lines and column. What I need is to clear the content written on them.

datagridview.datasource=null;
datagridview.resetbindings();
datagridview.Rows.Clear()
DataGridView1.DataSource=null; //Remover a datasource
DataGridView1.Columns.Clear(); //Remover as colunas
DataGridView1.Rows.Clear();    //Remover as linhas
DataGridView1.Refresh();    //Para a grid se actualizar
  • What is the Type of the object that was in Datasource ?

  • Bindingsource, a table.

  • With Datasource, a component, this is the case, it is preferable to use code that is much more practical. A Tip!

6 answers

3

You need to scroll through the rows and clear each cell as follows:

foreach (var row in dataGridView1.Rows)
{
    foreach (var cell in row.Cells)
    {
        cell.Value = ""; // ou qualquer outro valor que signifique 'limpar' no seu contexto
    }
}
  • I tried as well but the lines are clean and do not disappear, for example, I have a,datagrid with 10 lines, the code above cleans the content but it is the 10 lines. There’s another way to make the lines disappear without the columns disappearing?

2

At first the other forms described above did not work here, so...

This way removes all lines values etc, (gray pattern).

for (int i = 0; i < dataGridView1.RowCount; i++)
{
   dataGridView1.Rows[i].DataGridView.Columns.Clear();
}

1


Hello guys I solved my problem like this: Clear a dataDrid C#

dataGridView1.DataSource = null;

Then you just do:

dataGridView1.Columns.Add("Coluna", "Coluna");//Acrescenta colunas
dataGridView1.Columns.Add("Coluna2", "Coluna2");//Acrescenta colunas
dataGridView1.Rows.Add("A", "B");//Acrescenta Linhas
  • If the content comes from the database, you are creating a structure that will require maintenance in two locations, given any table changes.

0

        //LIMPAR GRID
        dataGridView1.Rows.Clear();
        dataGridView1.Refresh();
  • 2

    Could explain what these lines do?

  • 3

    The code seems to identify to the question, you changed only the capital letter to minuscula, I do not understand how this solves the problem. Could explain?

0

The lower command clears lines except the grid header

dataGridView2.Rows.Clear();

0

I usually use Dataset (Ds) as Datasource in Datagridview (DGV) and when I want to clean the grid I use the

DGV.DataSouce= Ds;
Ds.Clear(); //Retira os valores da tabela mantendo os campos

This way I can either clean the DMV or update it. I hope I’ve helped

Browser other questions tagged

You are not signed in. Login or sign up in order to post.