如何计算ASP.NET中gridview的总价格

时间:2017-07-24 09:29:49

标签: asp.net

我在ASP.NET中有一个gridview,在gridview中有一列总价格。我想显示gridview下面所有行的总价格,如果我要更新或删除任何行,那么它应该更新总计算价格。 任何人都可以请帮助。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

HTML标记由ASP.Net GridView组成。 ShowFooter属性设置为true,以便显示GridView的页脚行。 已为GridView启用了分页,并且已分配了OnPageIndexChanging事件处理程序。

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true"
OnPageIndexChanging="OnPageIndexChanging" ShowFooter="true">
<Columns>
    <asp:BoundField DataField="OrderID" HeaderText="Order ID" ItemStyle-Width="60" />
    <asp:BoundField DataField="ProductName" HeaderText="Product Name" ItemStyle-Width="210" />
    <asp:BoundField DataField="Price" HeaderText="Price" ItemStyle-Width="60" DataFormatString="{0:N2}"
        ItemStyle-HorizontalAlign="Right" />
</Columns>
</asp:GridView>
代码背后的代码。

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.BindGrid();
    }
}

private void BindGrid()
{
    string query = "SELECT TOP 30 OrderID,";
    query += "(SELECT ProductName FROM Products WHERE ProductID = details.ProductId) ProductName,";
    query += "(Quantity * UnitPrice) Price";
    query += " FROM [Order Details] details";
    query += " ORDER BY OrderID";
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    GridView1.DataSource = dt;
                    GridView1.DataBind();

                    //Calculate Sum and display in Footer Row
                    decimal total = dt.AsEnumerable().Sum(row => row.Field<decimal>("Price"));
                    GridView1.FooterRow.Cells[1].Text = "Total";
                    GridView1.FooterRow.Cells[1].HorizontalAlign = HorizontalAlign.Right;
                    GridView1.FooterRow.Cells[2].Text = total.ToString("N2");
                }
            }
        }
    }
}