Search code examples
asp.netdatalist

ASP.NET Datalist calculate field


I recently decided to implement tax on an ecommerce website I've built for fun more than anything and I've hit a stumbling block.

My implementation works well, tax is applied correctly etc, however a buddy pointed out to me today that prices on product pages are normally displayed inc tax.

I was thinking, rather than editing the Business and Data tier, I could change this on the DataList itself but I can't for the life of me work out how I'd actually do that. I've had a look in some text books and had a search around online but because I don't actually know what I'm looking for, I'm stuck :(.

Datalist:

<asp:DataList ID="list" runat="server" RepeatColumns="2" CssClass="ProductList" RepeatDirection="Horizontal" 
    Width="542px" EnableViewState="False" onitemcommand="list_ItemCommand">
<ItemTemplate>
<div style="width:271px;">
<h3 class="ProductName"><a href="<%# Link.ToProduct(Eval("ProductID").ToString()) %>"><%# HttpUtility.HtmlEncode(Eval("Name").ToString()) %></a></h3>
<a href="<%# Link.ToProduct(Eval("ProductID").ToString()) %>"><img width="100" border="0" src="<%# Link.ToProductImage(Eval("Thumbnail").ToString()) %>" alt='<%# HttpUtility.HtmlEncode(Eval("Name").ToString()) %>' /></a>
<%# HttpUtility.HtmlEncode(Eval("Description").ToString()) %>
<p>
<b>Price:</b>
<%# Eval("Price", "{0:c}") %>
</p>
<p>
<asp:Button ID="addToCartButton" runat="server" Text="Add to Basket" CommandArgument='<%# Eval("ProductID") %>' CssClass="SmallButtonText" />
</p>
</div>
</ItemTemplate>
</asp:DataList>

Code behind:

    // Retrieve the list of products in a Sub Category
    list.DataSource = CatalogAccess.GetProductsInSubCategory(subCategoryId, page, out howManyPages);
    list.DataBind();

E.g. if the price in the DB is £5, I'd need it to be displayed in the datalist above as £6 which includes the current UK VAT rate of 20%.

So: DBPrice * 1.2 = IncVatPrice

I hope this makes sense!

Thanks in advance, Matt


Solution

  • Instead of

    <%# Eval("Price", "{0:c}") %>
    

    use an expression somewhat similar to

    <%# String.Format("{0:c}", (Decimal)Eval("Price")*1.2) %>
    

    Or implement a function in codebehind:

    protected string IncludeVat(object dataItem)
    {
      Decimal price = (Decimal)DataBinder.Eval(dataItem, "Price");
      return String.Format("{0:c}", price * 1.2);
    }
    

    and call it in your DataList like that

    <%# IncludeVat(Container.DataItem) %>
    

    http://www.pluralsight-training.net/community/blogs/fritz/archive/2005/12/16/17507.aspx