Delete Multiple rows from datagridview

前端 未结 2 1415
离开以前
离开以前 2020-12-22 06:28

I\'ve a datagridview in which values are inserted.The gridview is like this.

    Item                PRID                 
   ------              ------              


        
相关标签:
2条回答
  • 2020-12-22 06:57

    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.

    I hope this helps.

    0 讨论(0)
  • 2020-12-22 06:58

    As mellamokb pointed out the reason is because your editing the collection during the foreach. One solution would be to store the rows with the same PRID in a list first and then remove them after. 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.

    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++;
    }
    
    0 讨论(0)
提交回复
热议问题