2012-01-05 106 views
0

我有下面的代碼,它試圖修改DataTable中的每一行,但在循環修改發生的行之後,當我查看行集合時,LOCATION列是即使循環剛剛填充它也是空的。誰能幫忙?在循環中修改DataTable行不會持續更改

 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(); 
      } 
     } 

回答

0

我不知道很多關於DataViews但我猜想,ToTable()是創建行的新實例。

嘗試修改循環到

foreach (DataRowView row in dtBoxes.DefaultView) 
{ 
    //.... 
} 
+0

謝謝你的工作,但它保持數據表的順序? – Jon 2012-01-05 12:29:00

+0

@Jon我不明白它會如何改變,但測試它。 – Ray 2012-01-05 13:17:46

0

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 
0

如果您正在使用一個DataTable,你需要採取另一種數據表,然後你需要通過在數據表中整個細胞循環如圖所示code.We不能修改排在同一個表,因爲它會拋出一個例外說「收集已修改」。我們必須採取一個新的數據表。

請考慮以下代碼。

 //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 = "&nbsp;"+oldVal; 
       row[i] = newVal; 
      } 
      dtUpdated.ImportRow(row); 
     } 

假設在上面的代碼中,通過採用新的數據表將「空間」添加到所有單元格的文本中。