首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从GridView中获取某列的合计值

从GridView中获取某列的合计值
EN

Stack Overflow用户
提问于 2013-04-16 21:20:44
回答 5查看 13.2K关注 0票数 3

我正在使用带有SQL-Server-2012的ASP.NET/VB.NET。

我有一个包含3个字段和1个模板字段的GridView列,如下所示:

代码语言:javascript
复制
<asp:GridView ID="grdItems" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="SqlDataSource3" Font-Names="Tahoma" ForeColor="#333333" GridLines="None">
    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
    <Columns>
        <asp:BoundField DataField="item_name" HeaderText="Item" SortExpression="item_name" />
        <asp:BoundField DataField="item_cost" HeaderText="Cost (inc. VAT)" SortExpression="item_cost" />
        <asp:BoundField DataField="item_quantity" HeaderText="Quantity" SortExpression="item_quantity" />
        <asp:TemplateField HeaderText="Sub-Total (inc. VAT)">
            <ItemTemplate>
                <asp:Label ID="TextBox3" runat="server" Text='<%# Convert.ToInt32(Eval("item_quantity")) * Convert.ToDouble(Eval("item_cost"))%>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <FooterTemplate>
                <asp:Label ID="lblTotalPrice" runat="server" />
            </FooterTemplate>                  
        </asp:TemplateField>
    </Columns>
    <EditRowStyle BackColor="#999999" />
    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" HorizontalAlign="Center" VerticalAlign="Middle" />
    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" HorizontalAlign="Center" VerticalAlign="Middle" />
    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
    <SortedAscendingCellStyle BackColor="#E9E7E2" />
    <SortedAscendingHeaderStyle BackColor="#506C8C" />
    <SortedDescendingCellStyle BackColor="#FFFDF8" />
    <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>

代码隐藏:

代码语言:javascript
复制
Imports System.Data.SqlClient
Imports System.Data

Partial Class ProjectReport
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load

        Dim ProjectID = Session("project_id")
        Session("ProjectID") = ProjectID

    End Sub
    Protected Sub grdItems_RowDataBound(sender As Object, e As GridViewRowEventArgs)

        Dim totalPrice As Decimal = 0

        If e.Row.RowType = DataControlRowType.DataRow Then


            Dim lblPrice As Label = DirectCast(e.Row.FindControl("lblTotalPrice"), Label)

            Dim price As Decimal = [Decimal].Parse(lblPrice.Text)


            totalPrice += price

        End If

        If e.Row.RowType = DataControlRowType.Footer Then
            Dim lblTotalPrice As Label = DirectCast(e.Row.FindControl("lblTotalPrice"), Label)

            lblTotalPrice.Text = totalPrice.ToString()


        End If
    End Sub


End Class

DataBound()

代码语言:javascript
复制
   Private Sub BindData()

        Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
        Dim query As New SqlCommand("SELECT Items.item_name, Items.item_cost, project_items.item_quantity FROM Items INNER JOIN project_items ON items.item_id = project_items.item_id WHERE project_items.project_id = @parameter", conn)

        query.Parameters.AddWithValue("@UserID", Session("ProjectID"))

        Dim da As New SqlDataAdapter(query, conn)

        da.SelectCommand = query

        Dim table As New DataTable()




        da.Fill(table)

        grdItems.DataSource = table
        grdItems.DataBind()
    End Sub

最后一列(模板字段)将quantity字段与cost字段相乘。

如何计算模板字段中的所有值(通过相加)?

EN

回答 5

Stack Overflow用户

发布于 2013-04-16 21:32:45

您必须使用数据绑定事件来求和这些值。查看this example并根据您的需求进行调整:

代码语言:javascript
复制
private Decimal OrderTotal;

protected void GridView1_DataBinding(object sender, EventArgs e)
{ 
    OrderTotal = 0.0M;
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //Keep adding the subtotal here
        OrderTotal += Subtotal;               
    }
}

protected void GridView1_DataBound(object sender, EventArgs e)
{      
    //Set a control with the total sum
    LabelOrderTotal.Text = OrderTotal.ToString("C");
}

基本上,您一直在RowDataBound事件中添加这些值,并在DataBound事件中设置一个带有总和的标签。或者,您可以在DataBound事件中迭代您的网格并添加所有内容。

票数 1
EN

Stack Overflow用户

发布于 2013-04-16 21:29:09

我个人会通过在RowDataBound事件中执行加法(实际上也是乘法)来做到这一点……

票数 0
EN

Stack Overflow用户

发布于 2013-04-16 21:33:16

遍历网格视图的DataBound事件上的所有DataRow行,并将TextBox3的值添加到一个正在运行的总变量中。

代码语言:javascript
复制
Protected Sub grdItems_DataBound(ByVal sender as Object, ByVal e as EventArgs) 
    Dim row As GridViewRow = Nothing
    Dim runningTotal As Double = 0.0
    For i As Integer = 0 to grdItems.Rows.Count
        row = grdItems.Rows(i)
        If row.RowType = DataControlRowType.DataRow Then
            ' Add error handling here
            runningTotal += Ctype(CType(row.FindControl("TextBox3"), Label).Text, Double)
        End If
    Next i
End Sub
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16038234

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档