neeko
neeko

Reputation: 2000

Add a Grand Total footer to GridView table VS 2010

I am trying to create a Grand Total of all values in a GridView table which will be displayed in the footer, I have started by creating the placeholder but not sure how to go about creating the grand total

        <FooterTemplate>
            <asp:Label ID="lblGrandTotal" runat="server" Text=""></asp:Label>
        </FooterTemplate>                  
    </asp:TemplateField>               
</Columns>

Upvotes: 0

Views: 2326

Answers (2)

Humpy
Humpy

Reputation: 2002

If you are adding up just a single column, this should work..

Code-Behind C#

decimal totalA = 0;

protected void gvAlexandria_RowDataBound(object sender, GridViewRowEventArgs e)
{
    string totalAmtFinanced = ((Label)gvVehicleTEMP.FooterRow.FindControl("lblTotalAmtFinanced")).Text;

    if (e.Row.RowType == DataControlRowType.DataRow)
    {        
        totalA += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "AmtFinanced"));
    }
    if (e.Row.RowType == DataControlRowType.Footer)
    {
        //Label lblTotal = (Label)e.Row.FindControl("lblTotal");

        if (totalAmtFinanced != null)
        {                   
            totalAmtFinanced = String.Format("{0:c}", totalA);
        }
    }
}

The column in my gridview that I am adding up is called AmtFinanced. This is how I total up a single column. If you have any problems, let me know!

Upvotes: 1

Ryuzaki
Ryuzaki

Reputation: 207

Hi in your gridview do this

<asp:TemplateField HeaderText="Amount">
    <ItemTemplate>
        <asp:Label ID="lblAmount" runat="server" 
                   Text='<%# Eval("Amount","0:N2}").ToString %>'>
        </asp:Label>
    </ItemTemplate>
    <FooterTemplate>
        <asp:Label ID="lblTotal" runat="server"></asp:Label>
    </FooterTemplate>
</asp:TemplateField>

Now declare like public

Private grdTotal As Decimal = 0

After in the event RowDataBound from your gridview

If e.Row.RowType = DataControlRowType.DataRow Then
    Dim rowTotal As Decimal =
    Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Amount"))
    grdTotal = grdTotal + rowTotal
End If
If e.Row.RowType = DataControlRowType.Footer Then
    Dim lbl As Label = DirectCast(e.Row.FindControl("lblTotal"), Label)
    lbl.Text = grdTotal.ToString("N2")
End If

Upvotes: 1

Related Questions