2016-03-15 27 views
-2

我想从我的Datagridview中删除行。这是我的DataGridView删除C#中的Datagriview行

enter image description here

这也是我用它来删除行

foreach (DataGridViewRow row in dataGridView.Rows) 
{ 
    if (Convert.ToInt32(row.Cells["Column28"].Value) < 2) 
    { 
     dataGridView.Rows.Remove(row); 
    } 
    else 
    { 
     if (Convert.ToInt32(row.Cells["Column29"].Value) < 6) 
     { 
      dataGridView.Rows.Remove(row); 
     } 
    } 
} 

的代码,但这样的结果我得到:

enter image description here

在哪里错误?

+0

什么问题?你期望什么? –

回答

1

foreach语句用于通过收集迭代,以获得您想要的信息,但可以用于添加从源集合中删除项目,以避免不可预知的副作用。

如果我们需要添加或删除源集合中的项目,请使用for循环。

for(int i =0; i< DataGridView.Rows.Count; i++)) 
{ 
    if (Convert.ToInt32(DataGridView.Rows[i].Cells["Column28"].Value) < 2) 
    { 
     DataGridView.Rows.RemoveAt(i); 
     i--; 
    } 
    else 
    { 
     if (Convert.ToInt32(DataGridView.Rows[i].Cells["Column29"].Value) < 6) 
     { 
      DataGridView.Rows.RemoveAt(i); 
      i--; 
     } 
    } 
} 
+0

非常感谢您的帮助 – user4340666