简体   繁体   English

在未绑定的数据网格视图中删除多行

[英]Deleting multiple rows in an unbound datagridview

I have a project that reads rows from an SQL database and displays them in a datagridview. 我有一个项目,该项目从SQL数据库读取行并将其显示在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). 您可以使用2个循环:第一个循环反转选定的项目,第二个循环删除选定的项目(这是反转之前先前未选择的项目)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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