Introduction:
In this article I will explain how to display the sum of total of columns in gridview footer using asp.net.
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
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. |
|||
|
|||
54 comments :
this code is not running for grid view this code is faq....
Freshers ke liye vardan hai ye website
Thank u very much!!!!
this code has error.But if u define varible(int total=0) globaly then it will work.
It is not working becoz i have datatype varchar(50).. what can i do
@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..
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
I have converted to int but Still it is printing total amount value 0.Kindly look at it.
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
Thanx Sir Now its working. Thanx a lot.
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
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
if i want same work with textbox , what can i do ?
am geeeting error as "Input Statament is not in a correct fromat"
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();
}
}
please respond to the post...its imp for me now
@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
if no records in DB .it will produce error Object cannot be cast from DBNull to other types.
Thanks Suresh your code is very helpful to improve my skills
valuable coding.
thanks.
I'm getting this error message
"Object reference not set to an instance of an object."
please help me
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
i have an error on this line.
lblamount.Text = total.ToString();
error is
Object reference not set to an instance of an object.
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;
}
}
}
Dear
You have to check whether lblamount is null or not so use -
if (lblamount != null) {
lblamount.Text = total.ToString;
}
This code is work but footer label doesnt display at runtime
I want to use data table to bind data in grid-view, in this case i am unable to display sum
It is showing this error
Object cannot be cast from DBNull to other types.
nice and clear post thanks dear suresh...
Can u give this example in telerik rad grid template column plss
tanks
good article can u please put vb.net code for this
Thanks a lot, Suresh Sir,
Its great but you are more great
From: LAKHPAT SINGH (JAGADHRI)
Somebody copied your article. Have a look : http://www.dotnetfunda.com/Blogs/Rajesh081725/4090/display-sum-of-columns-total-in-gridview-footer-in-aspnet
how to take footer template total value label to another label?
When Update the row total amount is not updating...can u help me..
sir i need your help so can you give me your no..
sir, my no. is 08906060343 so call me or missed calls me....
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?
nice articles suresh...it's very useful...
Thanx
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
how we can calculate totalprice= itemprice*quantity in gridview if both the values(itemprice and quantity) are entered by user in textbox
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.
execellent good job
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
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();
}
}
}
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
its working
What if the Amount is editable, then the total will not change, kindly reply soon or in mail id anuragintit@gmail.com
mark
How we show data in the sub group footer in grid view. Please help.
How can we add the Category sum of values in dynamically generated gridview when column names are unknown ?
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....
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.
Thank you very much. You saved me hours of looking for solutions
Note: Only a member of this blog may post a comment.