[英]Modifying DataTable rows in loop does not persist change
我有下面的代碼,試圖修改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();
}
}
如果您使用的是數據表,則需要獲取另一個數據表,然后需要遍歷數據表中的整個單元,如代碼所示。我們無法修改同一表中的行,因為它將引發異常,指出“集合已被修改“。我們必須獲取一個新的數據表。
考慮以下代碼。
//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);
}
假設在上面的代碼中,通過獲取一個新的數據表,在所有單元格的文本中添加了一個“空格”。
我對DataViews
不太了解,但是我猜想ToTable()
正在創建行的新實例。
嘗試將循環修改為
foreach (DataRowView row in dtBoxes.DefaultView)
{
//....
}
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();
}
}
dtBoxes.UpdateChanges() // Add this line and check
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.