TalhaAhmed
TalhaAhmed

Reputation: 70

Dynamically Calculate & Add value in a DataTable Column - ASP.Net C#

I have a DataTable which is being bound from DB with the Columns: Id, Date, Credit, Debit.

I want to add new Column "Balance" and its value should be calculated for EACH Row by the formula; [Balance in Previous row] - [Credit] + [Debit]

I have done something like this:

dt; //Filled & having columns ID, Date, Debit, Credit
dt.Columns.Add("Balance");

foreach(DataRow row in dt.Rows)
{
    //What should I do here to apply above formula
}

Upvotes: 0

Views: 1971

Answers (1)

msmolcic
msmolcic

Reputation: 6557

I suppose you want the formula for the first row to be Credit + Debit since there is no previous row and adapt the formula you wrote for any other row. If so, this would be the safe way to do it:

for (int i = 0; i < dt.Rows.Count; i++)
{
    DataRow row = dt.Rows[i];

    decimal credit = 0, debit = 0, previousBalance = 0;
    decimal.TryParse(row["Credit"].ToString(), out credit);
    decimal.TryParse(row["Debit"].ToString(), out debit);

    if (i > 0)
        decimal.TryParse(dt.Rows[i-1]["Balance"].ToString(), out previousBalance);

    row["Balance"] = i == 0 ? credit + debit : previousBalance - credit + debit;
}

Upvotes: 1

Related Questions