foreach 循环不会循环所有

本文关键字:循环 foreach | 更新日期: 2023-09-27 17:56:07

这是我的代码:

private void button_ok_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in dataGV_request.Rows)
        {
            if (row.Cells[1].Value != null)
            {
                if (row.Cells[1].Value.ToString() == "ACCEPT")
                {
                    ((dynamic)System.Windows.Forms.Application.OpenForms[row.Cells[0].Value.ToString()]).accept();
                    dataGV_connected.Rows.Add(false, row.Cells[0].Value);
                    dataGV_request.Rows.Remove(row);
                }
                else
                {
                    ((dynamic)System.Windows.Forms.Application.OpenForms[row.Cells[0].Value.ToString()]).deny();
                    dataGV_request.Rows.Remove(row);
                }
            }
        }
    }

它只做第一排,而不是全部。

谁能告诉我为什么?

提前致谢

foreach 循环不会循环所有

快速解决方案,切勿在 foreach 循环中修改集合。 将其更改为 for。

private void button_ok_Click(object sender, EventArgs e)
{
    for (int i = 0; i < dataGV_request.Rows.Count; i++)
    {
        DataGridViewRow row = dataGV_request.Rows[i];
        if (row.Cells[1].Value != null)
        {
            if (row.Cells[1].Value.ToString() == "ACCEPT")
            {
                ((dynamic)System.Windows.Forms.Application.OpenForms[row.Cells[0].Value.ToString()]).accept();
                dataGV_connected.Rows.Add(false, row.Cells[0].Value);
                dataGV_request.Rows.Remove(row);
                i--;
            }
            else
            {
                ((dynamic)System.Windows.Forms.Application.OpenForms[row.Cells[0].Value.ToString()]).deny();
                dataGV_request.Rows.Remove(row);
                i--;
            }
        }
    }
}