Monday, June 11, 2007

Formatting strings/numbers in .NET*

Monday, June 11, 2007 12:34:23 AM (GMT Standard Time, UTC+00:00)

Sometime ago I posted on formatting strings (specifically dates)  in .NET but I've found some more information so I thought I'd add to that post.

To start, I'll talk about the values that can be used in the BoundColumn.DataFormatString Property. This is the property used when formatting within databound controls (with a GridView or FormView for e.g.). The possible values for numbers range from C (currency), D (decimal), E (scientific or exponential) and even X (for hexadecimal). Then for for dates, there's "dd/MM/yyyy" etc. It's all really pretty simple to implement using like {0:C}, {0:dd/MM/yyyy} etc. For more formats you can check Custom Numeric Format Strings Output Examples.

The core of this post though is to point out a gotcha that you MUST be wary of when doing this formatting. And no, the gotcha is not the HTMLEncode that you must set to false, I mean beyond that! lol.

Now lately, I was trying to format a number into telephone format ###-####. I had the following inline code for a label (that was within a FormView template):

Text='<%# Bind("Telephone", "{0:###-####}") %>'

Looks all nice and correct huh? It should! Because I took it straight from this msdn site. For some reason however, this code was NOT working!!! The reason? At first I was totally lost! However after checking asp.net forums site, I FINALLY found a solution!

In my database the telephone field is actually a varchar, so in my DataSet, the telephone field came over as a String type. That was the problem!! If the field is of type String, the formatting does NOT work! The field must be of a number type (e.g. Int32, Decimal etc). So.. you can either change the datatype in the database (to a number type) or, CAST it in the SQL Select Query when you are retrieving it from the database.

Enjoy!!

Related posts:
Select a random row in MS SQL...
Regular expressions
VS2005, ASP.NET 2 & DLLs, DLLs..
MS's ASP.NET and.. PHP
2-way databinding cascading drop down lists within a FormView
ApplicationName Property when customising providers

Comments are closed.