I am having trouble finding the subtotal for the "price" column in the repeater control. It does not calculate the subtotal. Thanks in advance!
Here is the markup to the repeater:
<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>
Here is the code behind:
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();
}
}
Declare the variable outside of the ItemDataBound
event. The problem with your code is that ItemDataBound event is called after every row is bound to the repeater control, so every time your subtotal
& price
are getting initialized to 0
thus you are not getting the expected output.
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();
}
}