2010-11-05 26 views

回答

21
foreach (DataRow row in MyDataTable.Rows) 
{ 
row["columnNameHere" Or index] = value; 
} 
+0

1,因爲我忘記.Rows。 – GendoIkari 2010-11-05 17:23:05

10
foreach (DataRow row in myDataTable.Rows) 
{ 
    //do what you need to calculate myNewValue here 
    row["myColumn"] = myNewValue; 
} 

修訂添加.Rows。

1

除了使用for循環之外,它是一樣的。這確實是一個偏好問題。試試下面的代碼..

for (int i = 0; i <= myDataTable.Rows.Count - 1; i++){ 
        myDataTable.Rows[i]["ColumnName" Or IndexNumber] = value; 
} 
+0

這會工作,但我無法想象爲什麼你會使用它,而不是;這只是很多額外的代碼。 – GendoIkari 2010-11-05 17:56:29

1

如果你想改變指定列,你可以使用上面的代碼,但如果你想改變每個數據表中的內容,每一個細胞,然後我們需要創建另一個Datatable並使用「Import Row」如下所示進行綁定,如果我們不創建另一個表,它將拋出一個異常,並顯示「Collection was Modified」。

請考慮以下代碼。

//New Datatable created which will have updated cells 
      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); 
       } 

這將具有與前述Paranthesis({)所有小區