How do i compute the total and display it in GridView footer?

I have GridView with numerical data in one of the column, How do i compute the total and display it in my footer field?

Run live sample

 

<%@ Page Language="C#"%>
<%@ Import Namespace="System.Collections.Generic"%>
<script runat="server">

    private decimal amountSum;
    
    protectedvoid Page_Load(object sender, EventArgs e)
    {
        List<Account> data =new List<Account>();
        data.Add(new Account("Tom",12002));
        data.Add(new Account("Sam", 8900));
        data.Add(new Account("Harry", 15558));

        gridView.DataSource = data;
        gridView.DataBind();
        
    }

    string incrementSum(decimal amount)
    {
        amountSum += amount;
        return"";
    }

    publicclass Account
    {
        public Account(string name,decimal amount)
        {
            this.name = name;
            this.amount = amount;
        }
        
        privatestring name;
        private decimal amount;
        

        public decimal Amount
        {
            get { return amount; }
            set { amount = value; }
        }
	
        publicstring Name
        {
            get { return name; }
            set { name = value; }
        }
	
    }
    
    
</script>
<html>
<head id="Head1" runat="server">
    <title>GridView Summary</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView runat="server" ID="gridView" 
            AutoGenerateColumns="false" ShowFooter="True">
            <Columns>
                <asp:TemplateField HeaderText="#">
                    <ItemTemplate>
                        <%# Container.DataItemIndex + 1 %>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <%# Eval("Name") %>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Amount">
                    <ItemTemplate>
                        <%# Eval("Amount","{0:c0}") %>
                        <%# incrementSum((decimal)Eval("Amount")) %>
                    </ItemTemplate>
                    <FooterTemplate>
                        <%# amountSum.ToString("c0") %>
                    </FooterTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>
Bookmark with:
Technorati   Digg   Delicious   StumbleUpon   Facebook
My name is Jigar Desai I share my ideas on this site and you can contact me by filling contact form.

Categories