Friday, 8 April 2011

How to Display Sum Total in the Footer of the GridView Control

we will see how to display the sum total of a column in the footer of the Grid View control using Visual Studio 2008.
For the purpose of this article, we will use the Products Table  and the GridView control for data binding. The GridView control will display the data and SqlDataSource is supplied in the web.config file.

Our goal is to display the total of the column UnitPrice in the footer
By default, the GridView's Showfooter property is set to false. We'll change it to true. As we are calculating the field Price, we'll use TemplateField's ItemTemplate to display UnitPrice and Footer  to display the totalPrice.

<asp:GridView ID="GrdInvoice" runat="server" AutoGenerateColumns="false"  BorderColor="Black" Width="700px"   EmptyDataText="No Records are Available"      ShowFooter="true" 
onrowdatabound="GrdInvoice_RowDataBound"     AllowSorting="true"   >
            <asp:BoundField DataField="ItemNo" HeaderText="ItemNo" />
            <asp:BoundField DataField="ProductID" HeaderText="ProductID" />
            <asp:BoundField DataField="Quantity" HeaderText="Quantity" />
             <asp:TemplateField HeaderText="Price" >
         <asp:Label ID="lblTotal" runat="server" Text='<%# Eval("TotalItem").ToString() %>'></asp:Label>
            <HeaderStyle BackColor="BurlyWood" />

private decimal Total = (decimal)0.0;

protected void GrdInvoice_RowDataBound(object sender, GridViewRowEventArgs e)
        if (e.Row.RowType == DataControlRowType.DataRow)
            Total += Convert.ToDecimal((DataBinder.Eval(e.Row.DataItem, "TotalItem").ToString() == "" ? 0 : (DataBinder.Eval(e.Row.DataItem, "TotalItem"))));

        else if (e.Row.RowType == DataControlRowType.Footer)
            e.Row.Cells[3].Text = Total.ToString();
            e.Row.Cells[2].Text = "Total Price :";

In this article, you have learned how to display the sum total of a column in the footer of the GridView control with the help of an example.

  see the MSDN Library   Click

No comments:

Post a Comment