Following Error in this line.
datagridview1.Rows.Clear()
but this line gives error:
Cannot clear this list.
dataGridView1. Columns. Clear(); with the same results - number of columns was changed.
If your DataGridView is bounded, "dataGridView1. DataSource = null" is sufficient to clear it. If you want to Refresh it after a new fill, set the DataSource to null and restore it to what it was before, i.e. DataTable or BindingSource.
To clear GridView assign null to the GridView datasource.
When the Delete Button is clicked, the DataGridView CellContentClick event handler is executed. If the ColumnIndex is 3 i.e. the Delete Button is clicked, then a Confirmation MessageBox us show and if the User clicks Yes button the Row will be deleted (removed) from DataGridView and Database Table.
I also had similiar problem when I try to clear DataSource of a DataGridView after I had binded it to a DataTable with:
DataTable DT = ... ; // fill it
datagridview1.DataSource = DT;
when I try to clear it's rows later with the following code:
datagridview1.DataSource = null
I get this error:
ERROR: Object reference not set to an instance of an object
This object reference ERROR problem already solved in here. But I managed to solve my own problem (clearing DataGridView rows) with this code:
DataTable DT = (DataTable)datagridview1.DataSource;
if (DT != null)
DT.Clear();
I know that this question was asked a very long time ago, but I hope my solution would solve someone problems.
Is your DataGridView
bound to a DataSource
, i think thats why its not allowing you to clear it since its bound to an underlying DataTable
or List
.
you could try setting the DataSource Property to null
datagridview1.DataSource = null;
for clearing
private void button_Limpar_Click(object sender, EventArgs e)
{
DataTable DT = (DataTable)dataGridView_Cidade.DataSource;
if (DT != null)
DT.Clear();
}
#endregion
Simply add this line at beginning of your event:
dgv_nameOfGridView.DataSource=false;
Now every time you click it will erase the dgv..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With