【问题标题】:Modifying DataTable rows in loop does not persist change在循环中修改 DataTable 行不会持久更改
【发布时间】:2012-02-03 06:29:36
【问题描述】:
我有下面的代码,它试图修改 DataTable 中的每一行,但是在对发生修改的行进行循环之后,当我查看行集合时,即使循环只是填充了列 LOCATION 也是空的。有人可以帮忙吗?
dtBoxes.Columns.Add("LOCATION");
dtBoxes.DefaultView.Sort = "PALLETID";
foreach (DataRow row in dtBoxes.DefaultView.ToTable().Rows)
{
var locationRow = dtLocations.Select("ID = " + row["ID"].ToString());
if (locationRow != null)
{
row["LOCATION"] = locationRow.First()["LOCATION"].ToString();
}
}
【问题讨论】:
标签:
c#
.net
c#-4.0
.net-4.0
datatable
【解决方案1】:
我对@987654321@ 了解不多,但我猜ToTable() 正在创建行的新实例。
尝试将循环修改为
foreach (DataRowView row in dtBoxes.DefaultView)
{
//....
}
【解决方案2】:
dtBoxes.Columns.Add("位置");
dtBoxes.DefaultView.Sort = "PALLETID";
foreach (DataRow row in dtBoxes.DefaultView.ToTable().Rows)
{
var locationRow = dtLocations.Select("ID = " + row["ID"].ToString());
if (locationRow != null)
{
row["LOCATION"] = locationRow.First()["LOCATION"].ToString();
}
}
dtBoxes.UpdateChanges() // Add this line and check
【解决方案3】:
如果您使用的是 DataTable,您需要获取另一个 DataTable,然后您需要遍历数据表中的整个单元格,如代码所示。我们不能修改同一个表中的行,因为它会抛出异常“集合已修改”。我们必须采用新的数据表。
考虑下面的代码。
//To get the result with leading zero's in excel this code is written.
DataTable dtUpdated=new DataTable();
//This gives similar schema to the new datatable
dtUpdated = dtReports.Clone();
foreach (DataRow row in dtReports.Rows)
{
for (int i = 0; i < dtReports.Columns.Count; i++)
{
string oldVal = row[i].ToString();
string newVal = " "+oldVal;
row[i] = newVal;
}
dtUpdated.ImportRow(row);
}
假设在上面的代码中,通过一个新的数据表在所有单元格的文本中添加了一个“空格”。