简体   繁体   English

从数据网格视图中删除多行

[英]Delete Multiple rows from datagridview

I've a datagridview in which values are inserted.The gridview is like this.我有一个数据网格视图,其中插入了值。网格视图是这样的。

    Item                PRID                 
   ------              ------               
    Item1                1
    Item2                2
    Item3                2

I am trying to compare the PRID with a variable which holds the selected row PRID.我正在尝试将 PRID 与保存所选行 PRID 的变量进行比较。 What I've done so far.到目前为止我所做的。

                foreach (DataGridViewRow dgv_r in PurchaseOrder_dgv.Rows)
                {
                    if (dgv_r.Cells[1].Value.ToString() == CurrentSelected_PRID_ForPurchaseOrder.ToString())
                    {
                        PurchaseOrder_dgv.Rows.Remove(dgv_r);
                    }
                }

But it deletes the bottom row not the second row.and gives the following error.What I want is if the value of CurrentSelected_PRID_ForPurchaseOrder is equal to 2 then it should delete both the rows.I've tried it using for loop also but it gives me Index out of range error.It is giving the following error.但它删除了底行而不是第二行。并给出了以下错误。我想要的是,如果CurrentSelected_PRID_ForPurchaseOrder的值等于 2,那么它应该删除这两行。我也尝试过使用 for 循环,但它给出我索引超出范围错误。它给出了以下错误。

 Object Reference Not set to an instance of object

The are a couple of ways around this.有几种方法可以解决这个问题。 One is to do the following一是做到以下几点

for (int i = dataGridView1.RowCount - 1; i >= 0; i--)
    if (String.Compare(dataGridView1.Rows[i].Cells[1].Value.ToString(), "2") == 0)
        dataGridView1.Rows.Remove(dataGridView1.Rows[i]);

This is looping from the bottom end of the DataGridView and avoids the problem with removing rows whilst iterating.这是从DataGridView的底端循环,避免了在迭代时删除行的问题。

I hope this helps.我希望这有帮助。

As mellamokb pointed out the reason is because your editing the collection during the foreach.正如 mellamokb 指出的那样,原因是因为您在 foreach 期间编辑了集合。 One solution would be to store the rows with the same PRID in a list first and then remove them after.一种解决方案是先将具有相同 PRID 的行存储在列表中,然后再将其删除。 Something like this像这样的东西

var rowsToRemove = new List<int>();

foreach (DataGridViewRow dgv_r in PurchaseOrder_dgv.Rows)
{
    if (dgv_r.Cells[1].Value.ToString() == CurrentSelected_PRID_ForPurchaseOrder.ToString())
    {
        rowsToRemove.Add(dgv_r.Index);
    }
}

rowsToRemove.Reverse();
rowsToRemove.ForEach(i => PurchaseOrder_dgv.Rows.RemoveAt(i));

Another solution is to use a while loop instead which takes into account the possiblity of the collection size changing.另一种解决方案是使用 while 循环,它考虑了集合大小变化的可能性。

int i = 0;
while (i < PurchaseOrder_dgv.Rows.Count)
{
    if (PurchaseOrder_dgv.Rows[i].Cells[1].Value.ToString() == CurrentSelected_PRID_ForPurchaseOrder.ToString())
    {
        PurchaseOrder_dgv.Rows.RemoveAt(i);
    }
    i++;
}

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

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