日期:2014-05-18  浏览次数:20743 次

DataTable 使用 delete() 循环删除行的问题
DT 是表 有id 列

C# code


                string[] id = new string[] { "11", "13" };
                for (int i = 0; i < DT.Rows.Count; i++)
                {
                    for (int j = 0; j < id.Length; j++)
                    {
                        if (DT.Rows[i]["id"].ToString() == id[j])
                        {
                            DT.Rows[i].Delete();  // 不要使用 Remove(DT.Rows[i])
                        }
                    }
                }
               //这里也不许+  DT.AcceptChanges() 因为还要提交




  以下是:异常

  未处理 System.Data.DeletedRowInaccessibleException
  Message="不能通过已删除的行访问该行的信息。"
  Source="System.Data"
  




------解决方案--------------------
int iDtRowsCount; 
string[] id = new string[] { "11", "13" };
 for (int j = 0; j < id.Length; j++)
 {
iDtRowsCount = DT.Rows.Count;
for (int i = 0; i < iDtRowsCount ; i++)
{

if (DT.Rows[i]["id"].ToString() == id[j])
{
DT.Rows[i].Delete(); // 不要使用 Remove(DT.Rows[i])
break;
}
}
}
//这里也不许+ DT.AcceptChanges() 因为还要提交