How can I clear rows in DataGridView with C#?

后端 未结 13 2224
野的像风
野的像风 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: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.

提交回复
热议问题