如何在中继器中查找总价格

时间:2017-09-17 10:51:22

标签: c# asp.net repeater sqldatasource

我想在购物车中找到总价。我的“shop-cart.aspx”代码如下,如何在“shop-cart.aspx.cs”页面中找到总价?

<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1" OnItemDataBound="Repeater1_ItemDataBound">
    <ItemTemplate>
        <tr>
            <td class="text-left"><%#Eval("productname") %></td>
            <td class="text-left"><%#Eval("price") %></td>
            <td class="product-subtotal text-left"><%#Eval("piece") %></td>
        </tr>
    </ItemTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:aytasarimConnectionString %>" SelectCommand="SELECT * FROM [cart] WHERE ([userid] = @userid)">
    <SelectParameters>
        <asp:SessionParameter Name="userid" SessionField="userid" Type="Int32" />
    </SelectParameters>
</asp:SqlDataSource>

我试过这个但是我得到了null null。

string totalprice;
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        totalprice += Convert.ToDecimal(DataBinder.Eval(e.Item.DataItem, "price")) * Convert.ToDecimal(DataBinder.Eval(e.Item.DataItem, "piece"));
        LblTotalPrice.Text = totalprice;
    }
}

1 个答案:

答案 0 :(得分:1)

在ItemDataBound方法之外创建一个变量。然后将每个项目的价格添加到变量中并显示结果。

decimal total = 0;

protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    DataRowView item = e.Item.DataItem as DataRowView;
    total += Convert.ToDecimal(item["itemid"]);

    Label1.Text = string.Format("{0:C}", total);
}