Search code examples
c#asp.netrepeatersqldatasource

How Can I Find Total Price in the Repeater


I want to find the total price in the shopping cart. My "shop-cart.aspx" code is as follows, how can I find the total price in the "shop-cart.aspx.cs" page?

<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>

I've try this but I get en null error.

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;
    }
}

Solution

  • Create a variable outside the ItemDataBound method. Then add the price of every item to the variable and display the result.

    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);
    }