Tuesday, January 11, 2011

ASP.Net Gridview column totals

Most of the developers use repeater control, in case where they have to show the totals of a list  instead gridview control.
This is not that difficult to show the totals on the gridview itself on footer template. I will show the steps how to do this in this post.

 

Drag and drop a Gridview on your .aspx and bind the data.

eg: 

grd.DataSource = ds;
grd.DataBind();

on above code snippet grd is the my Gridview name and ds is my dataset. (you can use any datasource as your convenience)

Set the ShowFooter property to True of the GridView, this will show the footer on the Gridview.

Write the RowDataBound  event as follows, you can change the way you want. (in the following scenario I have not showed the declaration of chkAmount and transCharge 
decimal type variables, these two are class level varibles)

 

 

        protected void grd_RowDataBound(object sender, GridViewRowEventArgs e)
{

if (e.Row.RowType == DataControlRowType.DataRow)
{
chkAmount += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "ChkAmount"));
transCharge += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "TransCharge"));
}
else if (e.Row.RowType == DataControlRowType.Footer) // this is the footer identification
{
e.Row.Cells[4].Text = "Totals:";
// display totals on cells (in my case I have selected last 3 columns)
e.Row.Cells[6].Text = chkAmount.ToString("N2");
e.Row.Cells[5].Text = transCharge.ToString("N2");

}
}



 



Hope this is really easier when it comes to show totals on Gridview footer area . Please refer the following image which is the output of my above coding effort.



gridview-column-totals

0 comments:

My Achievements

Member of

Blog Archive

Followers

free counters