1.19. Adding a Totals Row to a DataGrid
Problem
You have a DataGrid 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 DataGrid,
accumulate the total for the data in the
ItemDataBound event handler, and then output the
total in the DataGrid footer.
In the .aspx file, set the
ShowFooter attribute of the
asp:DataGrid 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 then bind the data to the
DataGridin the normal fashion.In the
ItemDataBoundevent handler, add the values for each data row to the accumulated totals.In the
ItemDataBoundevent handler, set the total values in the footer when the footer is data bound.
Figure 1-24 shows some typical output. Examples
Example 1-57 through Example 1-59
show the .aspx file and code-behind files for an
application that produces this output.

Figure 1-24. DataGrid with totals row output
Discussion
The best way to describe the addition of a totals row to a
DataGrid is by example. In this recipe,
you’ll want to create the
DataGrid a little differently than normal. In the
asp:DataGrid element, set the
ShowFooter attribute to True to
cause a footer to be output when the control is rendered. You then
place the totals data in the footer.
<asp:DataGrid id="dgBooks" runat="server" BorderColor="000080" ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access