RedLight GreenLight
RedLight GreenLight

Reputation: 183

Programmatically Add Values To Grid View Footer

I have a grid view that displays values, I need to sum some of the values and display the sums in the footer. How can I control which column the sums display in?

Lets say for example if my grid view looks like this:

ID --- Name --- Store # --- # of Sales
1      Bob           123           14
2     Joe            456            21
3     Mike          818           10

So obviously I want my Total Sales Header to Display in

gvwSales.FooterRow.Cells[1].Text = "Total Sales";
gvwSales.FooterRow.Cells[4].Text = SUM(#ofSales);

But this logic does not add the info to my footer. How do I use this logic (or any other logic) to control the position that data is added to a grid view footer?

EDIT My ? is different than the suggested duplicate as they want to add the Sum in the last column, I want to add the sum in the footer.

Upvotes: 0

Views: 2952

Answers (1)

RedLight GreenLight
RedLight GreenLight

Reputation: 183

This is how I finally did it. I can provide further syntax if need be, but I think this will show how I achieved this.

protected void gvwSales_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        decimal tmptotalsales = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "totalsales").ToString());
        GrandTotalSales += tmptotalsales; 
    }      
    if (e.Row.RowType == DataControlRowType.Footer)
    {
        e.Row.Cells[0].Font.Bold = true;
        e.Row.Cells[3].Font.Bold = true;
        e.Row.Cells[0].HorizontalAlign = HorizontalAlign.Center;
        e.Row.Cells[3].HorizontalAlign = HorizontalAlign.Center;
        e.Row.Cells[0].Text = "Total Sales";
        e.Row.Cells[3].Text = GrandTotalSales.ToString("F");
    }
}

Upvotes: 1

Related Questions