How can I clear rows in DataGridView with C#?

后端 未结 13 2216
野的像风
野的像风 2020-12-03 18:19

Following Error in this line.

datagridview1.Rows.Clear()

but this line gives error:

Cannot clear this list.

相关标签:
13条回答
  • 2020-12-03 18:23
    private void button_Limpar_Click(object sender, EventArgs e)
    {
        DataTable DT = (DataTable)dataGridView_Cidade.DataSource;
        if (DT != null)
            DT.Clear();
    }
    #endregion
    
    0 讨论(0)
  • 2020-12-03 18:24

    You can use this simple method:

    First clear your DataTable and then refresh your DataGridView

    dataTable.Clear();
    dataGridView.Refresh();
    

    Hope this help

    0 讨论(0)
  • 2020-12-03 18:26

    First clear DataSource and then clear DataGridView

    in VB

     datagridview1.DataSource = Nothing
     datagridview1.Rows.Clear()
    

    hope help

    0 讨论(0)
  • 2020-12-03 18:28

    Easy solution is to clear the DataSet. ds.Clear();

    0 讨论(0)
  • 2020-12-03 18:33
    foreach (DataGridViewRow item in this.datagridview.Rows)
    {
        datagridview.Rows.RemoveAt(item.Index);
    }
    
    0 讨论(0)
  • 2020-12-03 18:34

    I had the same problem I tried with many solutions.

    In the end I realized that we can't clear the DataGridView if we use it's property "DGV.Datasource" because DGV takes its data from the dataset so you need to clear the DataTable rows

    Dataset.Tables["TableName"].Rows.Clear();
    

    If you use this function in the Load of the Form you need to add a condition

    if (DataSet.Tables["TableName"] !=null)    
        Dataset.Tables["TableName"].Rows.Clear();
    

    or you will get this error

    Object reference not set to an instance of an object.

    0 讨论(0)
提交回复
热议问题