如何计算行数据绑定事件中的总计

本文关键字:事件 数据绑定 何计算 计算 | 更新日期: 2023-09-27 18:27:38

我想把total列的总和作为一个总和。如何在rowdatabound事件中计算总计并显示在标签中?

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"   CssClass="gridview"  DataKeyNames="Id"  Width="633px" OnRowDataBound="GridView1_RowDataBound">

                    <Columns>
                        <asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="True" SortExpression="Id" />
                        <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
                        <asp:BoundField DataField="Quantity" HeaderText="Quantity" SortExpression="Quantity" />
                        <asp:BoundField DataField="UnitPrice" HeaderText="Unit Price" SortExpression="UnitPrice" />
                        <asp:BoundField DataField="Total" HeaderText="Total" SortExpression="Total" />
                    </Columns>
                </asp:GridView>

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            int value = Convert.ToInt32(e.Row.Cells[2].Text);
            int value2 = Convert.ToInt32(e.Row.Cells[3].Text);
            int total = value * value2;
            e.Row.Cells[4].Text = Convert.ToString(total);

    int GrandTotal = +total;
    lblgrandTotal = GrandTotal.ToString();
        }
    }

如何计算行数据绑定事件中的总计

您可以在现有的GridView1_RowDataBound事件中执行此操作,方法是将总计添加到每行的变量中,如下所示:-

 int grandTotal = 0;
 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            int value = Convert.ToInt32(e.Row.Cells[2].Text);
            int value2 = Convert.ToInt32(e.Row.Cells[3].Text);
            int total = value * value2;
            grandTotal += total;
            e.Row.Cells[4].Text = Convert.ToString(total);
            lblgrandTota.Text = grandTotal.ToString();
        }
    }

我已经将grandTotal变量放置在事件处理程序方法之外,这样就不会对每一行进行初始化。