我现在要实现一个功能,从excel文件中读取数据到inputTable中,然后对比数据库中的数据,查出重复的数据,并删除。但是现在只要找到了重复的数据,然后删除该行的时候下一次循环就报错,提示数据集已经改变!哪位给指导指导呀!谢谢了! foreach (DataRow dr in inputTable.Rows)
{
string conditions = "ISBN='" + dr["ISBN"].ToString() + "'"; if (ds_AllBooks.Tables[0].Select(conditions).Length > 0)
{
inputTable.Rows.Remove(dr);
inputTable.AcceptChanges();
break;
}
}
{
string conditions = "ISBN='" + dr["ISBN"].ToString() + "'"; if (ds_AllBooks.Tables[0].Select(conditions).Length > 0)
{
inputTable.Rows.Remove(dr);
inputTable.AcceptChanges();
break;
}
}
{
//删除操作!!
}
foreach是只读操作,你对数据源有任何修改都会导致错误
报这个错吧?foreach (DataRow dr in inputTable.Rows)//这个集合被改变了,所以报这个错
{
string conditions = "ISBN='" + inputTable.Rows[i]["ISBN"].ToString() + "'"; if (ds_AllBooks.Tables[0].Select(conditions).Length > 0)
{
inputTable.Rows.RemoveAt(i);
inputTable.AcceptChanges();//这个不要就行
break;
}
}
int rowsCount = inputTable.Rows.Count;
for(int i=0;i<rowsCount;i++)
{
....
}
for (int i = 0; i < inputTable.Rows.Count;i++ )
{
string conditions = "ISBN='" + inputTable.Rows[i]["ISBN"].ToString() + "'"; if (ds_AllBooks.Tables[0].Select(conditions).Length > 0)
{
inputTable.Rows.RemoveAt(i);
inputTable.AcceptChanges();
break;
}
}
inputTable.AcceptChanges();得放到循环外面
对.我忽略了这个问题.
但是如果把inputTable.Rows.Count先在外赋值,再去循环会报错的.最好别在循环里删.循环里只记录哪行要删,然后循环完后再删.
foreach (DataRow dr in inputTable.Rows)
{
string conditions = "ISBN='" + dr["ISBN"].ToString() + "'"; if (ds_AllBooks.Tables[0].Select(conditions).Length > 0)
{
al.Add(dr);
}
}
foreach (DataRow dr in al)
{
inputTable.Rows.Remove(dr);
inputTable.AcceptChanges();
}
我自己写了个简单的测试了一下
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("name", typeof(string));
for (int i = 0; i < 10; i++)
{
DataRow dr = dt.NewRow();
dr[0] = i;
dt.Rows.Add(dr);
}
Console.WriteLine(dt.Rows.Count);//输出10 ArrayList al = new ArrayList(); int count = dt.Rows.Count;
foreach(DataRow dr in dt.Rows)
{
if (dr[0].ToString() == "2")
{
al.Add(dr);
}
}
foreach (DataRow dr in al)
{
dt.Rows.Remove(dr);
} Console.WriteLine(dt.Rows.Count);//输出9
Console.ReadKey();
}
for (int i = 0; i < inputTable.Rows.Count;i++ )
{
string conditions = "ISBN='" + inputTable.Rows[i]["ISBN"].ToString() + "'"; if (ds_AllBooks.Tables[0].Select(conditions).Length > 0)
{
inputTable.Rows.RemoveAt(i);
inputTable.AcceptChanges();
break;
}
}
因为foreach有内建维,你要remove掉其中一个的话 接下来的循环肯定有问题.接分~~~~:)
{
string conditions = "ISBN='" + inputTable.Rows[i]["ISBN"].ToString() + "'"; if (ds_AllBooks.Tables[0].Select(conditions).Length > 0)
{
inputTable.Rows.RemoveAt(i);
inputTable.AcceptChanges();//这个不要就行
break;
}
}