我一直在寻找一种向GridView添加累计总列的方法,该列将显示该行中某个数字列的累计总数。所以基本上:
Points | Running Total
2 | 2
1 | 3
-0.5 | 2.5
1.5 | 4
我在cumulative totals using SQL Server和其他数据库上看到了一些问题,但我没有发现严格使用GridView而不更改任何SQL,所以我想我会在这里发布我的解决方案。
答案 0 :(得分:1)
该解决方案只处理RowDataBound并将给定字段的值添加到类的成员变量中。然后,该成员变量中的值显示在Running Total列中,该列包含用于此目的的标签。
在GridView aspx代码中:
<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>
这是RowDataBound处理程序的代码
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