【发布时间】:2013-02-16 11:00:21
【问题描述】:
我有一个 DataTable,dt2,我试图在其中添加新行(在下面代码的 else 块中)。我不能简单地在 foreach 循环中添加行(我尝试使用 dt2.Rows.Add(newRow); 行),因为这会破坏循环计数器或其他东西并导致以下错误:“集合已修改;枚举操作可能无法执行。 "
所以我尝试将新行值存储在列表中,然后将列表添加到循环外的表中。这在它编译并且确实添加了一些东西的意义上是有效的;不幸的是,它没有采用正确的值或列位置,而是显示这个废话:System.Collections.Generic.List`1[System.Object]
此外,信息应该显示在 Target_Folder、Target_File 和 Target_Checksum 下的第 3、4 和 5 索引列中,而不是在 Baseline_Folder 下。
如何在正确的列下存储和显示正确的值?
foreach (DataRow drow in dt2.Rows)
{
if (drow["BASELINE_FILE"].ToString() == filename)
{
// do stuff
}
else
{
newRow = dt2.NewRow(); // newRow is a DataRow I declared up above
newRow[3] = directory;
newRow[4] = filename;
newRow[5] = checksumList[j];
newRow[6] = "Missing";
//dt2.Rows.Add(newRow);
// can't add here because that increases the number of rows and screws up the foreach loop
// therefore need to find way to store these values and add outside of loop
newFiles.Add(newRow); // newFiles is a List
}
}
dt2.Rows.Add(newFiles); // this doesn't work properly, doesn't take correct values
【问题讨论】:
-
我面临同样的问题,任何人都可以提供解决方案,谢谢