Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove rows from DataGridView?

I have a winform with preloaded DataGridView over it...I want to remove rows from datagridview on selecting or highlighting the rows and clicking over the button...

Also want to clear all the columns....

Currently i used

foreach (DataGridViewRow dgvr in dataGridView2.Rows)
{
    if (dgvr.Selected == true)
    {
        dataGridView2.Rows.Remove(dgvr);
    }
}

but it is throwing an exception that "rows or not commited" or something....it would be appreciable if any one have any better suggestions....

like image 546
samj28 Avatar asked Jun 29 '12 08:06

samj28


People also ask

How to delete a row in a DataGridView c#?

Right click to select row in dataGridView The first thing you will want to do is to drag a contextMenuStrip from your toolbox to your form. Then you create a menu item "Delete Row" in the contextMenuStrip.


1 Answers

If you have AllowUserToAddRows enabled on your DataGridView then you might be accidently deleting the empty row at the bottom of the DataView which is a placeholder for the next user created row. Try disabling this option if not required, otherwise try using code like this:

foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
    if(!row.IsNewRow)
       dataGridView1.Rows.Remove(row);
}
like image 97
Adam Avatar answered Oct 03 '22 19:10

Adam