How can I clear rows in DataGridView with C#?

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

    Here we are 8 years later.

    Although

    datagridview1.DataSource = null;
    

    is a satisfactory answer for most, for me this removes all customizations I've added to the columns in design view. So hidden columns appears if I want to clear out the rows.

    So rather than clear out rows:

    datagridview1.Rows.Clear()
    

    Clear out the DataTable or DataView that you used to set up the DataGridView. Note you don't have to check if something is null nor worry about Object not set to reference errors.

    So here's how I did mine:

    //Populate the datagridview
    DataTable _DT = new DataTable();
    BindingSource _BS = new BindingSource();
    
    //Initially fill up your datatable with stuff
    //You can call this method again if data needed to be changed
    public void fillDT(int id) {
        _DT = fillUpDataTableWithStuffFromDB(id);
    
        _BS.DataSource = _DT.DefaultView;
        datagridview1.DataSource = _BS;
        _BS.ResetBindings(false);
    }
    
    //You can use this method to mimic the functionality above
    //But rather fetching data, just clear out the datatable and pass it in
    public void clearDT() {
        _DT.Clear();
        datagridview1.DataSource = _DT.DefaultView;
        datagridview1.Refresh();
    }
    

    As you can see above, I just cleared out the datatable, and passed that into the datagrid. This kept all my properties I set on the datagridview column.

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