smr5
smr5

Reputation: 2793

Sum the rows in Gridview

I want to sum up two columns in the gridview and show the total in the labels. I have paging enabled in the gridview.

Using this code I sum the totals of two columns, however, the total is for the selected page only.

How can I do a grand total to sum all the rows for selected columns from all the pages?

    decimal priceTotal = 0;
    int totalMinutes = 0;
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            priceTotal += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Total"));
            totalMinutes += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Duration"));
        }
        lblTotalPrice.Text = "Total Cost: $"+ priceTotal.ToString();
        lblTotalMinutes.Text = "Total duration: " + totalMinutes.ToString();
    }

Upvotes: 0

Views: 2495

Answers (1)

huMpty duMpty
huMpty duMpty

Reputation: 14470

decimal price = 0;
foreach (DataGridViewRow row in DataGridView.Rows)
{
     price += row.Cells["Total"]!=null ? Convert.ToDecimal(row.Cells["Total"].Value) : 0;
}

lblTotalPrice.Text = "Total Cost: $"+ price.ToString("n2");

Upvotes: 2

Related Questions