Displaying Total in Footer of GridView

During my training career, I have been asked one common question several times that how we can calculate summary totals inside GridView control and how we can show it at the footer of GridView control. So I have decided to write a tutorial on this topic. In this tutorial I will show you how you can calculate and display totals not only in GridView footer but also on any control outside GridView control.

For the purpose of this tutorial I have setup a simple ASP.NET page with data bound GridView control and a Label control on it. Following is the HTML source code of the GridView and Label control:

In the above code, I am using TemplateField column inside GridView control which has two templates ItemTemplate and FooterTemplate containing Label controls to show data. The Labels inside ItemTemplate are bound with UnitPrice and UnitsInStock fields using ASP.NET binding expression <%# %> syntax. The Labels inside FooterTemplate are left blank for showing totals later from the code.

I am also attaching an event handler for the RowDataBound event with the GridView. This event is where I will calculate the total for GridView data later. The RowDataBound event is raised whenever a row in the GridView is bound to data. It is raised for the header, the footer, and data rows. This event provides an opportunity to access each row before the page is finally sent to the client for display.

The Page_Load event of the page binds data with the GridView control as follows:

To calculate totals first you need to declare some variables outside the RowDataBound event. Two variables will keep track of the total of all the values bound inside GridView control and the third variable totalItems will be used to calculate the average price.

decimal totalPrice = 0M;
decimal totalStock = 0M;
int totalItems = 0;

As I mentioned above, RowDataBound event raised for all header, data or footer rows. I put one if condition to make sure currently it is binding DataRow. Then I am getting the reference of lblPrice and lblUnitsInStock labels using FindControl method. These labels have price and stock values of the current row in their text property. I am converting the text into decimal and then adding the value in totalPrice and totalStock variables. Once all the Data rows are finished I have similar check for Footer Row in which I am getting the reference of lblTotalPrice and lblTotalUnitsInStock Labels available in the FooterTemplate inside GridView and showing the totals on those labels.