GridView列の実行中/累積合計

エリック・バー

行の数値列の1つの累積合計を表示する累積合計列をGridViewに追加する方法を探していました。だから基本的に:

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

SQL Serverやその他のデータベースを使用した累積合計についていくつか質問がありましたが、SQLを変更せずにGridViewを厳密に使用することについては何も見つからなかったため、ここにソリューションを投稿しようと思いました。

エリック・バー

このソリューションは、RowDataBoundを処理し、指定されたフィールドの値をクラスのメンバー変数に追加するだけです。次に、そのメンバー変数の値が、その目的のラベルを保持する[現在の合計]列に表示されます。

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

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事