2.22. Adding a Totals Row to a GridView
Problem
You have a GridView
containing numeric information, and you need to display a total of the data in the last row of the grid.
Solution
Enable the output of the footer in the GridView
, accumulate the total for the data in the RowDataBound
event handler, and then output the total in the GridView
footer.
In the .aspx file, set the ShowFooter
attribute of the asp:GridView
element to True
.
In the code-behind class for the page, use the .NET language of your choice to:
Initialize the totals to
0
, and bind the data to theGridView
in the normal fashion.In the
RowDataBound
event handler, add the values for each data row to the accumulated totals.In the
RowDataBound
event handler, set the total values in the footer when the footer is data bound.
Figure 2-25 shows some typical output. Examples 2-63, 2-64 through 2-65 show the .aspx file and code-behind files for an application that produces this output.
Figure 2-25. GridView with totals row output
Discussion
The best way to describe the addition of a totals row to a GridView
is by example. In this recipe, youâll want to create the GridView
differently than normal. In the asp:GridView
element, set the ShowFooter
attribute to True
to cause a footer to be output when the control is rendered. Then, you place the totals data in the footer.
<asp:GridView ID="gvBooks" Runat="Server" AllowPaging="false" AllowSorting="false" ...
Get ASP.NET 2.0 Cookbook, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.