Congratulations to all monthly winners of May 2013 !!! They have won INR 2900 cash and INR 27497 worth prize.
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 9380 |  Welcome, Guest!   Register  Login
Home > Articles > ASP.NET > How to Display Total at the bottom of the Gridview?

How to Display Total at the bottom of the Gridview?

1 vote(s)
Rating: 3 out of 5
Article posted by Syedshakeer on 5/21/2009 | Views: 9694 | Category: ASP.NET | Level: Beginner red flag

Advertisements

Advertisements
In this Article I am going to explain you how to display a Toatal amount or Salary at the Footer of the Gridview.

First add one datagridevew on a webpage.Now i am going to retrive a data from a Table named 'emp'.This emp table has 3 columns
column name          DataType
-----------------------------------------------
id                          number
empname                varchar(50)
salary                     number

In Soucrce code .aspx page

create a Template in gridvew  to display Data as follows in between the <asp:Gridview>and </asp:Gridview>

<asp:GridView ID="GridView1" runat="server" Style="z-index: 100; left: 271px; position: absolute;

top: 68px" AutoGenerateColumns="False" Height="165px" ShowFooter="True" CellPadding="4"

ForeColor="Black" GridLines="Vertical" Width="229px" BackColor="White" BorderColor="#DEDFDE"

BorderStyle="None" BorderWidth="1px">

<Columns>

<asp:TemplateField HeaderText="ID">

<ItemTemplate>

<asp:Label ID="idlbl" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"id")%>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="NAME">

<ItemTemplate>

<asp:Label ID="namelbl" runat="server" Text-Align="right" Text='<%#DataBinder.Eval(Container.DataItem,"empname")%>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="SALARY">

<ItemTemplate>

<asp:Label ID="sal1" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"salary")%>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

</Columns>

<FooterStyle BackColor="#CCCC99" />

<RowStyle BackColor="#F7F7DE" />

<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />

<PagerStyle ForeColor="Black" HorizontalAlign="Right" BackColor="#F7F7DE" />

<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />

<AlternatingRowStyle BackColor="White" />

</asp:GridView>

write a code for display data in grdview:

in aspx.cs:

protected void Page_Load(object sender, EventArgs e)

{

SqlConnection conn = new SqlConnection("connectionstring");

conn.Open();

SqlDataAdapter ad = new SqlDataAdapter("select * from emp", conn);

DataSet ds = new DataSet();

ad.Fill(ds, "emp");

GridView1.DataSource = ds.Tables[0];

GridView1.DataBind();

}

Below is the simple output Image of a gridview:

Now we have calculate the Total Salary then have to dispaly Total Salary at the Bottom of the Gridview.By using <FooterTemplate><FooterTemplate> is used for the Last Line of our OutPut. eg:

<FooterTemplate>Last Line_outPut </FooterTemplate> 

NOTE:If we are using footer template we have to set ShowFooter Property as True by selecting the datagrid.

In this Example I am going to calculate the sum of Salary column.This sum should be displayed  in the salary column LastLine(bottom of the salary column).

I am using a method name as gettotal().here i am calculating the total salarys of employes.

public int gettotal()

{

SqlConnection conn = new SqlConnection("connectionstring");

conn.Open();

SqlCommand cmd = new SqlCommand("SELECT SUM(salary) FROM emp", conn);

int totalsal = Convert.ToInt32(cmd.ExecuteScalar());

return totalsal;

}

Next we have to use this gettotal () method in <FooterTemplate>

<FooterTemplate>
<%# gettotal()%>
</FooterTemplate>

here  <%# gettotal()%> will cal the gettotal() in aspx.cs page

we have to write use this FooterTemplate where we want a lastline output. Here I am using this FooterTemplate in salary column.

eg:

<asp:TemplateField HeaderText="SALARY">

<ItemTemplate>

<asp:Label ID="sal1" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"salary")%>'></asp:Label>

</ItemTemplate>

<FooterTemplate>

<%# gettotal()%>

</FooterTemplate>

</asp:TemplateField>

See the output Image

The aspx.page will look like as follows:

<%@ 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 id="Head1" runat="server">

<title>Untitled Page</title>

</head>

<body>

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

<div>

<asp:GridView ID="GridView1" runat="server" Style="z-index: 100; left: 271px; position: absolute;

top: 68px" AutoGenerateColumns="False" Height="165px" ShowFooter="True" CellPadding="4"

ForeColor="Black" GridLines="Vertical" Width="229px" BackColor="White" BorderColor="#DEDFDE"

BorderStyle="None" BorderWidth="1px">

<Columns>

<asp:TemplateField HeaderText="ID">

<ItemTemplate>

<asp:Label ID="idlbl" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"id")%>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="NAME">

<ItemTemplate>

<asp:Label ID="namelbl" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"empname")%>'></asp:Label>

</ItemTemplate>

<FooterTemplate>

<asp:Label ID="namelbl" runat="server" Text="Total"></asp:Label>

</FooterTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="SALARY">

<ItemTemplate>

<asp:Label ID="sal1" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"salary")%>'></asp:Label>

</ItemTemplate>

<FooterTemplate>

<%# gettotal()%>

</FooterTemplate>

</asp:TemplateField>

</Columns>

<FooterStyle BackColor="#CCCC99" />

<RowStyle BackColor="#F7F7DE" />

<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />

<PagerStyle ForeColor="Black" HorizontalAlign="Right" BackColor="#F7F7DE" />

<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />

<AlternatingRowStyle BackColor="White" />

</asp:GridView>

&nbsp;&nbsp;

</div>

</form>

</body>

</html>

the complete asp.cs page is:

protected void Page_Load(object sender, EventArgs e)

{

SqlConnection conn = new SqlConnection("connectionstring");

conn.Open();

SqlDataAdapter ad = new SqlDataAdapter("select * from emp", conn);

DataSet ds = new DataSet();

ad.Fill(ds, "emp");

GridView1.DataSource = ds.Tables[0];

GridView1.DataBind();

gettotal();

}

 

public int gettotal()

{

SqlConnection conn = new SqlConnection("connectionstring");

conn.Open();

SqlCommand cmd = new SqlCommand("SELECT SUM(salary) FROM emp", conn);

int totalsal = Convert.ToInt32(cmd.ExecuteScalar());

return totalsal;

}

Plz give me Feedback about this Article.

Advertisements

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

Experience:2 year(s)
Home page:http://www.dotnetfunda.com
Member since:Thursday, February 05, 2009
Level:Starter
Status: [Member]
Biography:Shakeer Hussain has completed his Master of Computer Applications degree from Deccan College of engg and technology of Osmania University.He is a MVM of www.dotnetspider.com.He has good experience in the areas of ASP.NET, C#.NET, VB.NET, SQL SERVER 2000/2005 and Windows Mobile. He has worked in Windows Mobile,Web Applicatin and ERP projects.
 Responses
Posted by: Avicool08 | Posted on: 21 May 2009 10:25:33 PM

Hey my sal is not 7k.....


never mind... its a good article...

Keep it up dude...



Posted by: RoOoSa | Posted on: 26 Feb 2011 04:50:44 AM | Points: 25

hi

I try to do this

public int gettotal()
{
SqlConnection conn = new SqlConnection("connectionstring");
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT SUM(salary) FROM emp", conn);
int totalsal = Convert.ToInt32(cmd.ExecuteScalar());

return totalsal;}

to show the sum in textbox or label and it's is work ok for me , but I got error when the gridview is empty or no row or value

Can you help me ?


>> Write Response - Respond to this post and get points
Related Posts

In this example i'll show how to detect the session timeout which occurs when user is idle for the time specified as Session.Timeout,using C# asp.NET and if it is than redirect the user to login page to login again, for this i've set time out value in web.config file to 1 minute

In this Article you can learn how to get a Selected Row Data from a DataList and display the data in textBoxes.

Through this article we will try to popup a child window and from there we will try to return a row data and populate into parent page using javascript.

.In ASP.NET we will have 2 types od Session Management. One is InProc where you store the data in the same system memory and the other one is OutProc where the memory will be stored in some other way like State Server or SQL Server. And there are many considerations while using OutProc in this mode we can store classes which serializable only. And most of the things in .NET like DataView, DataRow are not Serializable and cannot be placed in Session in this Mode

This is a example of populating three different DetailsView based on selection of of record in a GridView using Multiple DataKeyNames in C sharp and ASP .NET In this example GridView is populated from a table called Website using SqlDataSource, on GridVies i have defined multiple (3) DataKeyNames separated by comma, which will be used to fetch the record related to those DataKeyName from 3 tables in 3 DetailsViews

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 6/19/2013 3:12:20 PM