Eric Barr
Eric Barr

Reputation: 4155

Running / Cumulative total in GridView column

I was looking for a way to add a cumulative total column to my GridView that would show a cumulative total of one of the numeric columns in the row. So basically:

Points | Running Total
2      | 2
1      | 3
-0.5   | 2.5
1.5    | 4

I saw some questions on cumulative totals using SQL Server and other databases, but I found nothing about strictly using GridView without changing any SQL, so I thought I would post my solution here.

Upvotes: 1

Views: 2373

Answers (1)

Eric Barr
Eric Barr

Reputation: 4155

The solution simply handles RowDataBound and adds the value from the given field to a member variable of the class. Then the value in that member variable is displayed in the Running Total column, which holds a label for that purpose.

In the GridView aspx code:

<asp:GridView runat="server" ID="gvHistory" datasourceid="dsHistory" AutoGenerateColumns="false" AllowSorting="false" 
    onrowdatabound="gvHistory_RowDataBound">
        <Columns>
            <asp:BoundField HeaderText="Date" DataField="Date"  SortExpression="Date" DataFormatString="{0:d}" />
            <asp:BoundField HeaderText="Points" DataField="nPoints" />
            <asp:TemplateField HeaderText="Running Total">
                <ItemTemplate>
                    <asp:Label runat="server" ID="lblRunningTotal" Text=""></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
</asp:GridView>

And here is the code for the RowDataBound handler

Protected m_runningTotal As Double = 0

Protected Sub gvHistory_RowDataBound(sender As Object, e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then

        Dim pointsString As String = e.Row.DataItem("nPoints")
        Dim points As Double
        If Double.TryParse(pointsString, points) Then
            m_runningTotal = m_runningTotal + points

            Dim lblRunningTotal As Label = e.Row.FindControl("lblRunningTotal")
            lblRunningTotal.Text = m_runningTotal.ToString
        End If
    End If
End Sub

Upvotes: 2

Related Questions