简体   繁体   中英

Deleting multiple rows in an unbound datagridview

I have a project that reads rows from an SQL database and displays them in a datagridview. That part works great. I want to show a subset of these records by deleting every non selected row in the grid. This is the code:

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (!row.Selected)
    {
         if (!row.IsNewRow)
         {
              dataGridView1.Rows.Remove(row);
            //dataGridView1.Rows.Remove(dataGridView1.CurrentRow);
         }
     }    
}

It either deletes from the bottom up to the selected area and leaves the unselected rows above, or deletes selected as well as unselected rows.

Could anyone point me in the right direction?

The rows are being altered as others are being removed, so some elements are getting skipped incorrectly.

You could use 2 loops: the 1st to invert the selected items, and the 2nd to delete selected items (which would be the previously unselected items prior to inversion).

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    // invert row selections
    if (!row.Selected)
    {
        if (!row.IsNewRow)
        {
            row.Selected = true;
        }
    }
    else
    {
        row.Selected = false;
    }
}

// remove selected rows
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
    dataGridView1.Rows.Remove(row);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM