Get the Sum of a particular column values in a DataGrid


In this article, I am going to show how we can add a column value in a DataGrid. To add a column value in this programme I am using a function. In the function, I am passing the value of that particular column. Let us see how to do this through the below code.

The default.aspx code is:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>Count a column Value</title>

  </head>

    <body>

      <form id="form1" runat="server">

       <div>    

         <asp:DataGrid id="MyGrid" runat="server"   AutoGenerateColumns="False" CellPadding="2"

            CellSpacing="0"   BorderStyle="Solid" BorderWidth="4" Gridlines="Both"

            BorderColor="ActiveCaption"   ItemStyle-Font-Name="Verdana" ItemStyle-Font-Size="10pt" 

             HeaderStyle-Font-Name="Verdana" HeaderStyle-Font-Size="14pt"   HeaderStyle-Font-Bold="True"

              HeaderStyle-BackColor="#ccffcc" FooterStyle-Font-Name="Verdana" FooterStyle-Font-Size="10pt"

               FooterStyle-Font-Bold="True"   FooterStyle-ForeColor="White" FooterStyle-BackColor="Blue"

               OnItemDataBound="MyDataGrid_ItemDataBound" ShowFooter="True">

            

             <Columns>

                <asp:BoundColumn HeaderText="Product ID" DataField="ProductID" />

                <asp:BoundColumn HeaderText="Product Name" DataField="ProductName"/>

                <asp:BoundColumn HeaderText="Unit In Price" DataField="UnitPrice"

                     ItemStyle-HorizontalAlign="center"  > </asp:BoundColumn>

                <asp:BoundColumn HeaderText="Units In Stock" DataField="UnitsInStock"

                 ItemStyle-HorizontalAlign="center" HeaderStyle-HorizontalAlign="Center" >

                </asp:BoundColumn>

            </Columns>

         </asp:DataGrid>

       </div>

     </form>

  </body>

</html>


The Default.aspx.cs

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

 

public partial class _Default : System.Web.UI.Page

{

    private double TotalUnit = 0;

 

    protected void Page_Load(object sender, EventArgs e)

    {

        SqlConnection con = new SqlConnection("server=Localhost; database=Northwind; uid=sa;pwd=;");

        SqlCommand cmd = new SqlCommand("SELECT ProductID, ProductName,UnitPrice, UnitsInStock  FROM Products WHERE UnitPrice > 30", con);

        try

        {

            con.Open();

            MyGrid.DataSource = cmd.ExecuteReader();

            MyGrid.DataBind();

            con.Close();

        }

        catch (Exception ex)

        {

            //An error occured

            HttpContext.Current.Response.Write(ex.ToString());

        }

    }

 

    //This Method will calculate the column value

    private void MyTotalUnit(string Unit)

    {

        try

        {

            TotalUnit += Double.Parse(Unit);

        }

        catch

        {

            //A value was null

        }

    }

 

    //Here we are bionding the data to the datagrid

    public void MyDataGrid_ItemDataBound(object sender, DataGridItemEventArgs e)

    {

        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)

        {

            //Here we are passing the value of column in MyTotalUnit function to total

            MyTotalUnit(e.Item.Cells[3].Text);

            e.Item.Cells[3].Text = string.Format("{0:0}", Convert.ToDouble(e.Item.Cells[3].Text));

        }

        else if (e.Item.ItemType == ListItemType.Footer)

        {

            e.Item.Cells[0].Text = "Total";

            e.Item.Cells[3].Text = string.Format("{0:0}", TotalUnit);

        }

    }

}

When user run the application then the window will look like this:



Figure 1: Showing the total of Unit in stock.

Up Next
    Ebook Download
    View all
    Learn
    View all