c#DataGridView foreach运行次数少于预期

时间:2016-06-05 14:23:39

标签: c# loops datagridview foreach

我正在尝试搜索我的DataGridView但是我的foreach循环只运行了4次而不是行计数次...

private void btnPretrazi_Click(object sender, EventArgs e)
    {
        string naziv = "";
        foreach(DataGridViewRow row in dgvPretraga.Rows)
        {
            naziv = row.Cells["naziv"].Value.ToString();
            if (naziv.Contains(txtNaziv.Text))
            {
                Console.WriteLine("Yup = " + naziv);
            }
            else
            {

                dgvPretraga.Rows.Remove(row);
                Console.WriteLine("Not = " + naziv);
            }
        }
    }

控制台输出1(Anker):

Not = B.Disk gumeni FI 125
Not = Tipla Fe M16
Not = Rascepka Hus 300 8.0x90
Not = Civija Jus 230 6x70

控制台输出2(磁盘):

Yup = B.Disk gumeni FI 125
Not = B.Burgija Multi Gar.4-8
Not = Navratka Jus 602M 12x1.25
Not = Anker 753 12x100

它按预期工作,但它只运行4次,在DGV中有8行。 我做错了什么?

1 个答案:

答案 0 :(得分:1)

尝试删除此TER <- list(list(c(1,2,3),c(1,2,3,4)),list(c(1,2,3),c(1,2,3,4))) TER #[[1]] #[[1]][[1]] #[1] 1 2 3 #[[1]][[2]] #[1] 1 2 3 4 #[[2]] #[[2]][[1]] #[1] 1 2 3 #[[2]][[2]] #[1] 1 2 3 4 # Desired Output. TER #[[1]] #[[1]][[1]] #[1] 1 2 3 #[[1]][[2]] #[1] 1 2 3 4 以查看会发生什么。

dgvPretraga.Rows.Remove(row);

然后,您可以在删除行时循环调整代码和索引:

foreach(DataGridViewRow row in dgvPretraga.Rows)
{
    naziv = row.Cells["naziv"].Value.ToString();
    if (naziv.Contains(txtNaziv.Text))
    {
        Console.WriteLine("Yup = " + naziv);
    }
    else
    {
        // dgvPretraga.Rows.Remove(row);
        Console.WriteLine("Not = " + naziv);
    }
}