我无法找到"价格"的小计。转发器控件中的列。它不计算小计。提前谢谢!
以下是转发器的标记:
<asp:Repeater ID="rptItem" runat="server" OnItemCommand="rptItem_ItemCommand" OnItemDataBound="rptItem_ItemDataBound">
<HeaderTemplate>
<table id="carttable">
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Button ID="btnDelete" runat="server" Text="Delete" CommandName="delete" CommandArgument='<%# Eval("ProductId") %>' /></td>
<td>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("ImageUrl") %>' CssClass="imagecart" /></td>
<td>
<asp:HyperLink ID="HyperLink1" runat="server" Text='<%# Eval("ProductName") %>' NavigateUrl='<%# String.Concat("ProductDetails.aspx?ProductId=", Eval("ProductId")) %>'></asp:HyperLink></td>
<td>
<asp:Label ID="Label1" runat="server" Text='<%# String.Format("{0:C}", Eval("Price")) %>'></asp:Label></td>
<td>
<asp:TextBox ID="txtQty" runat="server" Width="50"></asp:TextBox><asp:Button ID="btnUpdate" runat="server" Text="update" /></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
Subtotal:
<asp:Label ID="lblSubtotal" runat="server" Text="Label"></asp:Label>
</FooterTemplate>
</asp:Repeater>
这是背后的代码:
protected void rptItem_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "delete")
{
List<Item> items = Session["Cart"] as List<Item>;
var productId = Convert.ToInt32(e.CommandArgument);
var itemToDelete = (from Item i in items
where i.ProductId == productId
select i).FirstOrDefault();
items.Remove(itemToDelete);
Session["Cart"] = items;
}
BindData();
}
protected void rptItem_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
double subtotal = 0;
double price = 0;
if (e.Item.ItemType == ListItemType.Item)
{
price += Convert.ToDouble(DataBinder.Eval(e.Item.DataItem, "Price"));
subtotal += price;
}
if (e.Item.ItemType == ListItemType.Footer)
{
Label lblSubtotal = (Label)e.Item.FindControl("lblSubtotal");
lblSubtotal.Text = subtotal.ToString();
}
}
答案 0 :(得分:2)
在ItemDataBound
事件之外声明变量。您的代码的问题是在每行绑定到转发器控件之后调用ItemDataBound事件,因此每次subtotal
&amp; price
已初始化为0
,因此您无法获得预期的输出。
double subtotal = 0;
double price = 0;
protected void rptItem_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item)
{
price += Convert.ToDouble(DataBinder.Eval(e.Item.DataItem, "Price"));
subtotal += price;
}
if (e.Item.ItemType == ListItemType.Footer)
{
Label lblSubtotal = (Label)e.Item.FindControl("lblSubtotal");
lblSubtotal.Text = subtotal.ToString();
}
}