How can I correctly delete multiple rows in a datagridview control?

Hi, I want to delete the selected rows in a datagridview that has a datatable as a datasource.  I loop through the selected rows one by one but then I get a excption error that indexing is out of bound.  The indexing changes when I deleting one by one so that doesn't work.  Any good way to get this done?  Thanks.
        private void btnMulExclude_Click(object sender, EventArgs e)
        {
            DataGridView dgvForMapping, dgvExclude;

            if (filterUser)
            {
                dgvForMapping = dgvSource;
                dgvExclude = dgvFiltered;
            }
            else
            {
                dgvForMapping = dgvGroupSource;
                dgvExclude = dgvGroupFiltered;

            }

            if (dgvForMapping.SelectedRows.Count <= 0)
            {
                MessageBox.Show("Please select at least 1 row to filter.");
                return;
            }
            DataRow drTarget, drSource;
            DataRowView drv;
            int rowsToExclude = dgvForMapping.SelectedRows.Count;


            for (int index = 0; index < rowsToExclude; index++)
            {
                drTarget = tblExcludeRows.NewRow();
                drv = (DataRowView)(dgvForMapping.SelectedRows[index].DataBoundItem);
                drSource = drv.Row;
                CUnityDS.InsertDataRow(ref drTarget, drSource);
                tblExcludeRows.Rows.Add(drTarget);
                drSource.Delete();
            }
            dgvExclude.DataSource = tblExcludeRows;
            dgvForMapping.Refresh();
            dgvExclude.Refresh();    

        }
lapuccaAsked:
Who is Participating?
 
iHadiCommented:
Hi lapucca

Try using the following code to remove selected rows from a dataGridView Control:

            foreach (DataGridViewRow dr in dataGridView1.SelectedRows)
                dataGridView1.Rows.Remove(dr);
0
 
lapuccaAuthor Commented:
That worked perfectly.  Thanks.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.