For循环每次运行只删除一行DataGridView

时间:2015-09-19 09:39:11

标签: c# loops datagridview

我有一个功能,用户选择一个数字并单击一个按钮,它会比较特定列的行,如果该数字小于select,则会删除整行。但是我的for循环每次只检查1行,即使它在for循环中也是如此。

我的代码:

int result = 0;
if (int.TryParse(txtLessThanFollowersCount.Text.Trim(), out result))
{
    for (int i = 0; i < dataGridView1.RowCount; i++)
    {
        int parse;
        if (int.TryParse(txtLessThanFollowersCount.Text.Trim(), out parse))
        {
            if (Int32.Parse(dataGridView1.Rows[i].Cells[3].Value.ToString()) < parse)
            {
                dataGridView1.Invoke(new Action(() => dataGridView1.Rows.RemoveAt(i)));
            }
        }
    }
}
else
{
    MessageBox.Show("Error in the follower count selection", "Error");
}

1 个答案:

答案 0 :(得分:1)

试试这段代码:

int result = 0;
        if (int.TryParse(txtLessThanFollowersCount.Text.Trim(), out result))
        {
            for (int i = dataGridView1.RowCount - 1; i >= 0; i--)
            {
                int parse;
                if (int.TryParse(txtLessThanFollowersCount.Text.Trim(), out parse))
                {
                    if (Int32.Parse(dataGridView1.Rows[i].Cells[3].Value.ToString()) < parse)
                    {
                        dataGridView1.Invoke(new Action(() => dataGridView1.Rows.RemoveAt(i)));
                    }
                }
            }
        }
        else
        {
            MessageBox.Show("Error in the follower count selection", "Error");
        }

我所做的是从最后一行到第一行迭代遍历各行。当你删除一行时,修改了集合并且索引改变了, 因为当您删除第一行时(如果满足条件),第二行将成为第一行。 (因为第一排消失了!)得到了吗? :P

所以从最后开始迭代解决了这个问题:)

希望这会有所帮助..