我如何在OnitemDatabound(ASP.NET)中找到我的购物车总数



我想在购物车中找到商品的总价格。但是,如果该产品的价格打折,我必须获得折扣价,如果没有折扣价,我必须获得总价正常的价格。

这是我的中继器:

<asp:Repeater ID="RptrShoppingCart" runat="server" OnItemDataBound="RptrShoppingCart_ItemDataBound">
    <ItemTemplate>
        <asp:Label ID="LblProductPrice" runat="server" Text='<%#int.Parse(Eval("DiscountedPrice").ToString()) > 0 ? Convert.ToDecimal(Eval("DiscountedPrice")) * Convert.ToDecimal(Eval("Piece")) : Convert.ToDecimal(Eval("NormalPrice")) * Convert.ToDecimal(Eval("Piece")) %>'></asp:Label>
    </ItemTemplate>
</asp:Repeater>
<asp:Label ID="LblShoppingCartTotal" runat="server"></asp:Label>

注意:我没有故意编写中继器填充代码

和我的C#代码:

decimal total = 0;
protected void RptrShoppingCart_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    DataRow dr = function.GetDataRow("SELECT Product.DiscountedPrice FROM ShoppingCart AS SC INNER JOIN Product AS P ON SC.ProductID = P.ID WHERE SC.UserID = '" + Session["UserID"] + "'");
    DataRowView item = e.Item.DataItem as DataRowView;
    if (Convert.ToDecimal(dr["DiscountedPrice"]) > 0) // This means if it is a discounted price
    {
        total += Convert.ToDecimal(item["DiscountedPrice"]) * Convert.ToDecimal(item["Piece"]);
    }
    else
    {
        total += Convert.ToDecimal(item["NormalPrice"]) * Convert.ToDecimal(item["Piece"]);
    }
    LblShoppingCartTotal.Text = string.Format("{0:C}", total);
}

例如:我添加了一个正常价格的1件产品:10 $,但价格折扣价:8 $,并添加2件产品,价格为正常价格:20 $没有折扣价。

购物车的总和应为:(1 x 8 $( (2 x 20 $(= 48 $ ,但我的购物车看起来为8 $。我在哪里做错?

您做得很好,您只是在页面生命周期的错误部分中设置了标签。

这是最后一个生命周期事件之一,因此您不会出错。

    protected override void OnPreRender(EventArgs e)
    {
        LblShoppingCartTotal.Text = string.Format("{0:C}", total);
    }

最新更新