foreach循环不循环所有

时间:2014-04-02 15:20:59

标签: c# foreach

这是我的代码:

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

        }
    }

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

谁能让我知道为什么?

提前致谢

1 个答案:

答案 0 :(得分:0)

快速解决方案,永远不要在foreach循环中修改集合。将其更改为。

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

    }
}