Asp.NET Tutorials
Home > Asp.Net开发 > Add a total row to a GridView

Hot archives

Add a total row to a GridView

one common piece of functionality that I've often found myself doing is adding totals to a GridView. Generally, the concept involves using the RowDataBound event, keeping a total of each column and then adding this total to a new label in each column. The problem with this method is that it isn't re-usable since the next GridView you create probably won't have the same columns in it.

To combat this, I've created a function that accepts a GridView as a parameter, loops through it and creates the total row for you. It then returns the GridView so that you can use it on your page.

Let's start by creating a simple page which contains a GridView:

  1. <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default1.aspx.vb" Inherits="Default1" Debug="true"&nbsp;&nbsp;%>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml" >  
  6. <head runat="server">  
  7.     <title>Untitled Page</title>  
  8. </head>  
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.     <div>  
  12.         <asp:GridView ID="GridView1" runat="server">  
  13.         </asp:GridView>  
  14.     </div>  
  15.     </form>  
  16. </body>  
  17. </html>  

Now, let's add the code behind for this page that will populate the GridView with some sample data:
  1. Imports System.Data   
  2. Partial Class Default1   
  3.     Inherits System.Web.UI.Page   
  4.   
  5.     Protected Sub Page_Load(ByVal sender As ObjectByVal e As System.EventArgs) Handles Me.Load   
  6.         ' Check for a postback   
  7.         If Not Page.IsPostBack Then  
  8.             ' Bind the Gridview with some sample data   
  9.             GridView1.DataSource = GetData()   
  10.             GridView1.DataBind()   
  11.         End If  
  12.     End Sub  
  13.   
  14.     Private Function GetData() As DataTable   
  15.         ' Declarations   
  16.         Dim dt As New DataTable   
  17.         Dim dr As DataRow   
  18.   
  19.         ' Add some columns   
  20.         dt.Columns.Add("Column1")   
  21.         dt.Columns.Add("Column2")   
  22.         dt.Columns.Add("Column3")   
  23.         dt.Columns.Add("Column4")   
  24.         dt.Columns.Add("Column5")   
  25.         dt.Columns.Add("Column6")   
  26.         dt.Columns.Add("Column7")   
  27.   
  28.         ' Add some test data   
  29.         For i As Integer = 0 To 10   
  30.             dr = dt.NewRow   
  31.             dr("Column1") = i   
  32.             dr("Column2") = "Some Text " & (i * 5)   
  33.             dr("Column3") = (i * 7)   
  34.             dr("Column4") = "Some More Text " & (i * 10)   
  35.             dr("Column5") = (i * 8)   
  36.             dr("Column6") = (i * 9)   
  37.             dr("Column7") = (i * 10)   
  38.             dt.Rows.Add(dr)   
  39.         Next  
  40.   
  41.         ' Return the DataTable   
  42.         Return dt   
  43.     End Function  
  44.   
  45. End Class  
  46.   


If you run this page, you'll see a simple GridView that has some sample data in it. Some of the columns are numeric, some aren't. There is also no total row.

Now, here's the function I use to loop through the GridView and create the total row. It accepts the GridView as the first parameter, a boolean value to state whether you want the first column to be totalled (the word "Totals:" will be added if not) and an optional CSS class for the total row. The resulting GridView with the total row will then be returned back to the page.
  1.     Private Function AddTotalRowToGridView(ByVal Grid As GridView, ByVal ShowTotalTextInFirstColumn As Boolean, _   
  2.                                                 Optional ByVal FooterCSSClass As String = ""As GridView   
  3.            
  4.         ' Declarations   
  5.         Dim dtTotals As New System.Data.DataTable   
  6.         Dim dr As System.Data.DataRow = dtTotals.NewRow   
  7.         Dim intTemp As Integer = 0   
  8.   
  9.         ' Create a column for each of the GridView's Cells   
  10.         For iColumn As Integer = 0 To (Grid.Rows(0).Cells.Count - 1)   
  11.             dtTotals.Columns.Add("Column" & iColumn)   
  12.         Next  
  13.   
  14.         ' Loop through each of the GridView's Rows   
  15.         For iRow As Integer = 0 To (Grid.Rows.Count - 1)   
  16.             If iRow = 0 AndAlso ShowTotalTextInFirstColumn = True Then  
  17.                 dr("Column0") = "Totals:"  
  18.             Else  
  19.                 ' Make sure the row type is a DataRow   
  20.                 If Grid.Rows(iRow).RowType = DataControlRowType.DataRow Then  
  21.                     ' Loop through each Cell   
  22.                     For iCurrentColumn As Integer = 0 To (Grid.Rows(0).Cells.Count - 1)   
  23.                         ' Add the value to the total if it is an Integer   
  24.                         If Integer.TryParse(Grid.Rows(iRow).Cells(iCurrentColumn).Text, 0) _   
  25.                             AndAlso Not (iCurrentColumn = 0 And ShowTotalTextInFirstColumn = TrueThen  
  26.                             ' If the current value is null, add the value to the total   
  27.                             If IsDBNull(dr("Column" & iCurrentColumn)) Then  
  28.                                 dr("Column" & iCurrentColumn) = CInt(Grid.Rows(iRow).Cells(iCurrentColumn).Text)   
  29.                             Else  
  30.                                 ' If we already have a total, add this value to that total   
  31.                                 intTemp = CInt(dr("Column" & iCurrentColumn))   
  32.                                 intTemp += CInt(Grid.Rows(iRow).Cells(iCurrentColumn).Text)   
  33.                                 dr("Column" & iCurrentColumn) = intTemp   
  34.                                 ' Reset the temp variable   
  35.                                 intTemp = 0   
  36.                             End If  
  37.                         End If  
  38.                     Next  
  39.                 End If  
  40.             End If  
  41.         Next  
  42.   
  43.         ' Add the totals row to our totals DataTable   
  44.         dtTotals.Rows.Add(dr)   
  45.   
  46.         ' Turn on the footer in the GridView   
  47.         Grid.ShowFooter = True  
  48.         Grid.FooterRow.Visible = True  
  49.   
  50.         ' Add the totals to the footer row   
  51.         For iFooterColumn As Integer = 0 To (Grid.FooterRow.Cells.Count - 1)   
  52.             Grid.FooterRow.Cells(iFooterColumn).Text = dtTotals.Rows(0).Item(iFooterColumn).ToString   
  53.         Next  
  54.   
  55.         ' Add the CSS class   
  56.         If Not String.IsNullOrEmpty(FooterCSSClass) Then  
  57.             Grid.FooterRow.CssClass = FooterCSSClass   
  58.         End If  
  59.   
  60.         'Return the Grid   
  61.         Return Grid   
  62.   
  63.     End Function  

Add this function to your code-behind page and after you've called the DataBind method of the GridView (in the Page Load event), call this function like so:
  1.             ' Add the total row   
  2.             GridView1 = AddTotalRowToGridView(GridView1, False"gridView")   

You'll now see a total row with a total for each column that has numeric values in it.

Possible Enhancements

* Add an optional parameter for the text to be displayed if the column is not numeric (e.g. "N/A")
* Inherit the GridView control and add this functionality to it

Add by : Huobazi (2007-4-18:09:25)