Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Display sum of columns total in gridview footer in asp.net

Feb 22, 2011
Introduction:

In this article I will explain how to display the sum of total of columns in gridview footer   using asp.net.


Description:

I have a one gridview with multiple rows and columns and for that gridview paging also has enabled now my requirement I need to display sum of all the columns (Total) in gridview footer for that I have used gridview row databound condition this functionality will work for paging enabled gridview also. Before proceed to functionality first we need to design one table in database and give name EmployeeSalary

 

ColumnName
DataType
EmpID
Int(set identity property=true)
EmpName
varchar(50)
Location
varchar(50)
Amount
varchar(50)
After completion table creation enter some dummy and design your aspx page like this


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Show gridview Rows Total in </title>
<style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvEmp" CssClass="Gridview" HeaderStyle-BackColor="#61A6F8" HeaderStyle-ForeColor="White" HeaderStyle-Font-Bold ="true" DataKeyNames="EmpID" runat="server" ShowFooter="true" AllowPaging="true" PageSize="5" AutoGenerateColumns="false" DataSourceID ="sqldsEmp" onrowdatabound="gvEmp_RowDataBound">
<FooterStyle Font-Bold="true" BackColor="#61A6F8" ForeColor="black" />
<Columns>
<asp:BoundField DataField="EmpID" HeaderText="Emp ID" />
<asp:BoundField DataField="EmpName" HeaderText="Emp Name" />
<asp:TemplateField  HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server" Text='<%#Eval("Location") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lbltxttotal" runat="server" Text="Total Amount"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:Label ID="lblamount" runat="server" Text='<%# Eval("Amount") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sqldsEmp" runat="server" SelectCommand="select * from EmployeeSalary" ConnectionString="<%$ ConnectionStrings:dbconnection %>">
</asp:SqlDataSource>
</div>
</form>
</body>
</html>
 
After completion of aspx page write the following code in codebehind

int total = 0;
protected void gvEmp_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType==DataControlRowType.DataRow)
{
total += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Amount"));
}
if(e.Row.RowType==DataControlRowType.Footer)
{
Label lblamount = (Label)e.Row.FindControl("lblTotal");
lblamount.Text = total.ToString();
}
}

After that set your database connection in web.config like this because we are using this connection in our sqldatasource to get the data from database


<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"/>
</connectionStrings >


Demo


If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

54 comments :

Anonymous said...

this code is not running for grid view this code is faq....

Uday Prabhat Gangwar said...

Freshers ke liye vardan hai ye website
Thank u very much!!!!

Anonymous said...

this code has error.But if u define varible(int total=0) globaly then it will work.

sundar said...

It is not working becoz i have datatype varchar(50).. what can i do

Suresh Dasari said...

@sundar
Here we are converting varchar(50) data to int format by using conversion in row databound condition.Please check your code i think there is problem with your coding..

Brij said...

Nice post!!!
Now, we can take advantage of Linq without using template field...May be one line code to do it. See following:

http://goo.gl/FKgHs

Anonymous said...

I have converted to int but Still it is printing total amount value 0.Kindly look at it.

Suresh Dasari said...

i think that problem because of int total=0 inside of row databound condition declare int total=0 globally and try to debug your code and check whether your getting values in rowdatabound condition or not

Anonymous said...

Thanx Sir Now its working. Thanx a lot.

Anonymous said...

Can you provide a code for "Remember Me on this Computer" in Login Page? I have tried,Cookies have been created but i am not able to retrieve the values from cookies and check by database. Sir, Pls help me in this.

Kunal Chaturvedi

Naresh said...

Hi Suresh Dasari,
I have been reading your blog for past one week .
It is a superb blog
I like so much,and can you provide how to write the above code in stored procedures

Mansoob said...

if i want same work with textbox , what can i do ?

jyo said...

am geeeting error as "Input Statament is not in a correct fromat"

jyo said...

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}

}

private void BindData()
{
SqlDataAdapter da = new SqlDataAdapter("select marks from marks ", con);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
public int total = 0;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType==DataControlRowType.DataRow)
{
//Label Marks = (Label)e.Row.FindControl("Marks");

total += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "marks"));
}
if(e.Row.RowType==DataControlRowType.Footer)
{
Label lblamount = (Label)e.Row.FindControl("lblTotalmarks");
lblamount.Text = total.ToString();
}
}

jyo said...

please respond to the post...its imp for me now

Suresh Dasari said...

@jyo....
Please check your aspx code also during bind values to gridview and please debug your code and check whether your getting values in rowdatabound condition or not

Anonymous said...

if no records in DB .it will produce error Object cannot be cast from DBNull to other types.

Anonymous said...

Thanks Suresh your code is very helpful to improve my skills

Unknown said...

valuable coding.


thanks.

Anonymous said...

I'm getting this error message
"Object reference not set to an instance of an object."
please help me

G.Anil Kumar said...

in my gridview i have two textboxes in itemtemplate one is quantity and other is amount.i need total amount in another cell.i want code for calculating in javascript or jquery

Anonymous said...

i have an error on this line.
lblamount.Text = total.ToString();

error is

Object reference not set to an instance of an object.

Unknown said...

protected void GridView2_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) {
total += Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "amt"));
}
if (e.Row.RowType == DataControlRowType.Footer) {
Label lblamount = (Label)e.Row.FindControl("lblTotal");
if (lblamount != null) {
lblamount.Text = total.ToString;
}
}
}

Unknown said...

Dear

You have to check whether lblamount is null or not so use -

if (lblamount != null) {
lblamount.Text = total.ToString;
}

Anonymous said...

This code is work but footer label doesnt display at runtime

Anonymous said...
This comment has been removed by the author.
Anonymous said...

I want to use data table to bind data in grid-view, in this case i am unable to display sum

Unknown said...

It is showing this error

Object cannot be cast from DBNull to other types.

Bhagwat Prasad Sharma said...

nice and clear post thanks dear suresh...

Anonymous said...

Can u give this example in telerik rad grid template column plss



tanks

Anonymous said...

good article can u please put vb.net code for this

Unknown said...

Thanks a lot, Suresh Sir,
Its great but you are more great
From: LAKHPAT SINGH (JAGADHRI)

Anonymous said...

Somebody copied your article. Have a look : http://www.dotnetfunda.com/Blogs/Rajesh081725/4090/display-sum-of-columns-total-in-gridview-footer-in-aspnet

Anonymous said...

how to take footer template total value label to another label?

suresh sunkara said...

When Update the row total amount is not updating...can u help me..

Unknown said...

sir i need your help so can you give me your no..

sir, my no. is 08906060343 so call me or missed calls me....

Anonymous said...

i want a button click to do the sum of one sql column then display it in textbox (asp.net)

what syntax should i use?

Anonymous said...

nice articles suresh...it's very useful...

Anonymous said...

Thanx

Unknown said...

sir i need ur help urgently cn u plz mention ur emailid here so that i cn explain my prblm through mail in detail. you cn send me test mail my id is kamnatara12@gmail.com. Thanks in advance

Unknown said...

how we can calculate totalprice= itemprice*quantity in gridview if both the values(itemprice and quantity) are entered by user in textbox

Krish said...

HI nice tutorial..As am a beginner in .Net, am confusing with one of my question. The thing is, am having a content in one column as 8:7:15, 9:15:12,and 10:3:4. My question is, How to add these three rows and produce in footer of Grid view as 27:25:31.Any help would be more helpful to me. Thanks in advance.

Gowtham Gambir said...

execellent good job

ashish said...

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}

}

private void BindData()
{
SqlDataAdapter da = new SqlDataAdapter("select marks from marks ", con);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
public int total = 0;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType==DataControlRowType.DataRow)
{
//Label Marks = (Label)e.Row.FindControl("Marks");

total += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "marks"));
}
if(e.Row.RowType==DataControlRowType.Footer)
{
Label lblamount = (Label)e.Row.FindControl("lblTotalmarks");
lblamount.Text = total.ToString();
}
}
it is not add total then post correct code

ashish said...

THIS CODE IS CORRECT USE IT



public partial class hello : System.Web.UI.Page
{
decimal totalPrice = 0M;
int totalItems = 0;
SqlConnection con = new SqlConnection();
protected void Page_Load(object sender, EventArgs e)
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["pos1"].ConnectionString;
if (con.State == ConnectionState.Closed)
{
con.Open();
}
if (!IsPostBack)
{
data();
}
}
private void data()
{

SqlDataAdapter da = new SqlDataAdapter("select id,item,price from southindian where selected=1", con);
DataTable table = new DataTable();

da.Fill(table);

Gridview1.DataSource = table;
Gridview1.DataBind();
}

protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblPrice = (Label)e.Row.FindControl("lblPrice");


decimal price = Decimal.Parse(lblPrice.Text);


totalPrice += price;

totalItems += 1;
}

if (e.Row.RowType == DataControlRowType.Footer)
{
Label lblTotalPrice = (Label)e.Row.FindControl("lblTotalPrice");


lblTotalPrice.Text = totalPrice.ToString();



}
}
}

debu said...

Hi please can any one tell how to this thing in asp.net vb language . try this once it show in the textbox from the footer row value but ones the auto post the text box value change to 0.00 why ???

please reply me my id deburoy1910@gmail.com

Anonymous said...

its working

Anurag said...

What if the Amount is editable, then the total will not change, kindly reply soon or in mail id anuragintit@gmail.com

Nikita said...

mark

Anonymous said...

How we show data in the sub group footer in grid view. Please help.

Anonymous said...

How can we add the Category sum of values in dynamically generated gridview when column names are unknown ?

Unknown said...

hi friends
in my side i am using the ui-grid in that grid the aggregation is not working and how to show the total qty in footer....

Ranjan Kumar Yadav said...

Hi sir,Please Write article on How to calculate Total Sum of Textbox Inside Gridview itemtemplate. and show total sum on label inside footer item template using javascript or Jquey.

Tech said...

Thank you very much. You saved me hours of looking for solutions

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.