【问题标题】:Running / Cumulative total in GridView columnGridView 列中的运行/累计总数
【发布时间】:2014-04-28 13:42:53
【问题描述】:
我正在寻找一种将累积总计列添加到我的 GridView 的方法,该列将显示该行中一个数字列的累积总计。所以基本上:
Points | Running Total
2 | 2
1 | 3
-0.5 | 2.5
1.5 | 4
我在cumulative totals using SQL Server和其他数据库上看到了一些问题,但是我没有发现在不更改任何SQL的情况下严格使用GridView,所以我想我会在这里发布我的解决方案。
【问题讨论】:
标签:
asp.net
vb.net
gridview
【解决方案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