How can I clear rows in DataGridView with C#?

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

    You have to Clear datasource not datagridview rows.

    datagridview1.DataSource = null;
    

    Another way is

    1) Dont assign direct datasource to gridview. add rows from datatable to gridview

          foreach (DataRow row in dataTable.Rows)
            {
                var dataGridRow = new DataGridViewRow();
                dataGridRow.CreateCells(datagridview1);
    
                for (int i = 0; i < row.ItemArray.Length; i++)
                {
                    dataGridRow.Cells[i].Value = row.ItemArray[i];
                }
    
                datagridview1.Rows.Add(dataGridRow);
            }
    

    then use

    datagridview1.Rows.Clear()
    

提交回复
热议问题