2012-01-05 8 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

+0

@ジョン私はそれがどのように変化するかわかりませんが、テストします。 – Ray

0

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 
0

あなたがたDataTableを使用している場合は、別のDataTableを取る必要があり、その後、あなたがcode.Weに示すように、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 = "&nbsp;"+oldVal; 
       row[i] = newVal; 
      } 
      dtUpdated.ImportRow(row); 
     } 

上記のコードでは、新しいデータテーブルを取ることによってすべてのセルのテキストに「スペース」が追加されたとします。

関連する問題