开发者

ASP.NET c# adding row to dataset

开发者 https://www.devze.com 2023-03-14 02:00 出处:网络
i have a dataset which im using to calculate some sales figures, this data set has about 15 columns i want to add a new row to the end of the dataset to calculate the total of each column. heres an ex

i have a dataset which im using to calculate some sales figures, this data set has about 15 columns i want to add a new row to the end of the dataset to calculate the total of each column. heres an example of what the dataset looks like

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

so what i want to be able to do开发者_JAVA技巧 is add another row at the end which will calulate the sum of each row so it would look something like

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

so far i have

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


Have a look at the DataTable.Compute method:

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

You would call this function only once, for example:

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

Edited according to your new informations


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消