Saturday, 18 August 2007

Formatting Bound Repeater Item fields

I was starting to get annoyed with the look of the values in the Price column of a products table i was building.

I was using a Repeater which was bound to a DataSet returned from an SQL Stored Procedure. The price column in the SQL table was of type small money. This resulted in the bounds price coloumn generating values with four decimal places.

After searching around i found that the DataBinder.Eval method actually has an overloaded constructor which accepts a format string.

I changed the code in my .aspx file from this:

<%# Eval("Price") %>

To this:

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

And the result was a colomn populated with the same values, but with a currency sign out the front, in my case the £, and formatted to only two decimal values.

Problem licked!

For more information on the options available to you with the format string, see:


and this article on the BoundField.DataStringFormat property. This particular property is not made available by the Repeater control (or its children) but the information in that article does, in my opinion, a better job of explaining how formatting strings work.

But it was a short lived solution...I have some client-side scripts working out the subtotals of purchases by handling the onchange event of each Quantity textbox. This stopped working after i changed the format of the price column.

This was because i was introducing the currency character (£) into the value of the price table cell, while my code was expecting just a decimal number. So i could either:

1. Strip the currency character out of the TableCell.InnerText field
2. Introduce a new element into the TableCell e.g. an asp:Label element, give the new element the bound value and then place a static '£' character within the table cell. Finally, just pass the value of Label.Text to the client side function.

I try to avoid introducing spurious markup into my presentation where ever possible, so i'm leaning against option 2. However, since i'm using Visual Studio, perhaps my reasoning for going against option 2 is pointless...for example, i already use a few controls, and they just evaluate to elements anyway.

So, i decided to use another control.

I changed the code in the aspx to:

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

This gave the desired output but for some reason when i went to read in the value from the label empty string would be returned:

Label price = (Label)e.Item.FindControl("lblPrice");
// price control would be found but price.Text would be ""

Then i realised that you can't actually have any content in between the start and end tags of an control but instead i needed to bind the data to the label's Text property.

Now we're cooking!

No comments:

Post a Comment