1

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 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
    }
1

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

4 Comments

am i correct in thinking that i call the above function in my for each loop ?
@c11ada: no, this function needs to be called only once, because dt.Compute("Sum(Total)", null) will sum up already the total-column of all rows implicitely. Have a look at the Link i've provided.
i tried your method but all that seems to do is add an empty row and column !! please look at the update it might clarify what im trying to achieve
@c11ada: i've edited my answer according to your new informations.
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.