• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1203
  • Last Modified:

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();    

        }
0
lapucca
Asked:
lapucca
1 Solution
 
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

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now