2011-06-17 125 views
1

我有一個數據集,即時通訊使用來計算一些銷售數字,這個數據集有大約15列,我想添加一個新的行到數據集的末尾來計算每個柱。繼承人什麼樣的數據集看起來像ASP.NET c#添加行到數據集

NAME | GP | ORD_GP | EXP | TOTAL GP 
a  206  48  -239  15 
b  0  27  0  27 

爲例所以我希望能夠做的就是添加另一排在末尾,這將calulate每一行的總和所以它會看起來像

NAME | GP | ORD_GP | EXP | TOTAL GP 
a  206  48  -239  15 
b  0  27  0  27 
TOTAL 206  75  -239 42 

到目前爲止,我已經

ds.Tables[0].Rows.Add("TOTAL"); 
    foreach (DataColumn dc in ds.Tables[0].Columns) 
    { 
     // add upp column data and put into toal field 
    } 
+0

的可能重複[我怎樣才能動態地添加colums and rows to a empty dataset?](http://stackoverflow.com/questions/5712509/how-can-i-dynamically-add-colums-and-rows-to-an-empty-data設置) – 2011-06-17 10:14:33

回答

4

看一看的DataTable.Compute方法:

private void AddTotalRow(DataTable dt) 
{ 
    DataRow dr = dt.NewRow(); 
    dr["NAME"] = "TOTAL"; 
    dr["GP"] = dt.Compute("Sum(GP)", null); 
    dr["ORD_GP"] = dt.Compute("Sum(ORD_GP)", null); 
    dr["EXP"] = dt.Compute("Sum(EXP)", null); 
    dr["TOTAL_GP"] = dt.Compute("Sum(TOTAL_GP)", null); 
    dt.Rows.Add(dr); 
} 

你會調用該函數只有一次,例如:

AddTotalRow(ds.Tables[0]); 
//Now the first DataTable in your DataSet has an additonal record with the total values 

根據新的信息

+0

我正確認爲我在每個循環中調用上述函數? – c11ada 2011-06-17 10:44:49

2

編輯How to: Add Rows to a DataTable

DataRow newCustomersRow = dataSet1.Tables["Customers"].NewRow(); 

newCustomersRow["CustomerID"] = "ALFKI"; 
newCustomersRow["CompanyName"] = "Alfreds Futterkiste"; 

dataSet1.Tables["Customers"].Rows.Add(newCustomersRow);