利用 OdbcConnection,OdbcCommand,OdbcDataAdapter 的对象
连接数据库,执行select语句,语句如下:select * from XXX然后得到一个数据集,用如下的循环访问每一个DataRow:
try
{
    foreach (DataRow cRow in cSectionsSet.Tables[0].Rows)
   {
        Debug.WriteLine("ID = " + cRow["ID"] + " Name = " + cRow["Name"]);
   }
}
catch (Exception cException)
{
    string strMsg = cException.Message;
}结果时不时的(不是每一次都这样)在循环时发生异常,异常的消息是:
Collection was modified; enumeration operation might not execute.
为什么?如何解决?搞了2天没有解决。

解决方案 »

  1.   

    提示很明显呀,datatable发生了变化
      

  2.   

    to 可能有,函数的外部可能有循环,其中有访问同一数据表的代码,但是不一定是
    同一个数据表。
    退一步讲,就算多线程访问并写了数据库,那又怎么了?难道数据库不支持多用户访问不是不能多线程访问数据库的问题,而是你在外边修改了记录集,因此用foreach会有问题,自己做循环处理。

    changeforeach (DataRow cRow in cSectionsSet.Tables[0].Rows)
    {
    Debug.WriteLine("ID = " + cRow["ID"] + " Name = " + cRow["Name"]);
    }withfor( int i = 0; i < cSectionsSet.Tables[0].Rows.Count; i++ )
    {
         DataRow cRow = cSectionsSet.Tables[0].Rows[i];   
         Debug.WriteLine("ID = " + cRow["ID"] + " Name = " + cRow["Name"]);
    }
      

  3.   

    这样修改的原因是,你在其他线程中有可能修改了cSectionsSet.Tables[0].Rows这个collection。那么会造成无法按照如下的方式进行正常运行,
    foreach (DataRow cRow in cSectionsSet.Tables[0].Rows)而改为for( int i = 0; i < cSectionsSet.Tables[0].Rows.Count; i++ )
    能最大的避免错误。
      

  4.   

    table.rows都被修改了,还想foreach??
      

  5.   

    用for都不行道理很简单,循环到的纪录有可能已经不存在
      

  6.   


    To Knight94(愚翁)
    thanks for your reply, you are a nice administrator.
    But you said in your reply : program can avoid error as more as possible.
    I think it means program can not resolve this problem completely, it's a regret.
    actually i do not change anything in any thread else, i only read data after i
    got it. maybe i made other mistake that i have not awared so far.so we can assume i modified data in other thread and go on this discussing, i 
    do not know if you have any better idea else ?to yiming0755()
    Could you talk about it any more ?
      

  7.   

    Safe explain as follows:
    for( int i = 0; i < cSectionsSet.Tables[0].Rows.Count; i++ )//There's safe
    {
    DataRow cRow = cSectionsSet.Tables[0].Rows[i];// But there is not safe, because other theads maybe modify row collection
    Debug.WriteLine("ID = " + cRow["ID"] + " Name = " + cRow["Name"]);
    }So you should write code like this:
    for( int i = 0; i < cSectionsSet.Tables[0].Rows.Count; i++ )
    {
        try
        {
    DataRow cRow = cSectionsSet.Tables[0].Rows[i];
    Debug.WriteLine("ID = " + cRow["ID"] + " Name = " + cRow["Name"]);
    }
    catch{ continue;}
    }