For循环的问题

jstzcl007 2014-09-25 01:50:25
foreach里嵌套了2个for循环,编译时提示第2个for循环无法访问到
foreach (DataGridViewRow currentrow in dataGridView2.Rows)
{
string str_jhbh = currentrow.Cells["jhbh"].Value.ToString();
for(int int_row=0;int_row<dataGridView3.Rows.Count;int_row++)
{
if(dataGridView3.Rows[int_row].Cells["jhbh_jh"].Value.ToString()==str_jhbh)
{
dataGridView3.Rows[int_row].Cells["kcsl"].Value = Convert.ToInt32(dataGridView3.Rows[int_row].Cells["kcsl"].Value.ToString()) +
Convert.ToInt32(currentrow.Cells["xssl"].Value.ToString());
dataGridView3.Rows[int_row].Cells["thsl_jh"].Value=Convert.ToInt32(dataGridView3.Rows[int_row].Cells["thsl_jh"].Value.ToString())-
Convert.ToInt32(currentrow.Cells["thsl"].Value.ToString());
break;
}
}
for(int int_row=0;int_row<dataGridView4.Rows.Count;int_row++)//这句提示无法访问的代码
{
if (dataGridView4.Rows[int_row].Cells["mxbh_mx"].Value.ToString() == currentrow.Cells["mxbh"].Value.ToString())
dataGridView4.Rows.RemoveAt(int_row);
break;
}
dataGridView2.Rows.Remove(currentrow);
}
...全文
115 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
卧_槽 2014-09-25
  • 打赏
  • 举报
回复
for(int int_row=0;int_row<dataGridView4.Rows.Count;int_row++)//这句提示无法访问的代码 把int_row改为 i 试试。
白衣如花 2014-09-25
  • 打赏
  • 举报
回复
foreach确实不能修改集合 但是for还是可以的,只有要注意索引 dataGridView4.Rows.RemoveAt(int_row--); 假设把第4行移除了,下一行还是第四行,所以此处的--与步长++抵消掉
烈火蜓蜻 2014-09-25
  • 打赏
  • 举报
回复
你在Foreach里,修改集合的东西,是会抛异常的, dataGridView2.Rows.Remove(currentrow);这一句, 你改变了Rows的集合数据,会出错的。
於黾 2014-09-25
  • 打赏
  • 举报
回复
还有 if (dataGridView4.Rows[int_row].Cells["mxbh_mx"].Value.ToString() == currentrow.Cells["mxbh"].Value.ToString()) dataGridView4.Rows.RemoveAt(int_row); break; 这里确定不用加{}?? 你这是不管if走不走,都直接break了
於黾 2014-09-25
  • 打赏
  • 举报
回复
没看出有什么问题 全部重新生成一下试试 有可能代码不一致,导致报错的行错误
by_chance 2014-09-25
  • 打赏
  • 举报
回复
如果是绿条的警告,而不是红条的错误不理会也行
by_chance 2014-09-25
  • 打赏
  • 举报
回复
执行以后那里报错?
by_chance 2014-09-25
  • 打赏
  • 举报
回复
dataGridView2.Rows.Remove(currentrow); 应该是这句吧,不要在循环里remove表格 可以先用array存下来,然后从最后一行开始往前remove

110,567

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧