Format telephone number??

B

bernadou

Ok, this is yet again one of those things that is driving me crazy. How do I
use a formatting expression to format a number? Here's what I'm trying, but,
it isn't working.

Text='<%# Eval("fldPhone", "(###)-###-####") %>'

What I'm trying to see happen is the value "3335551212" output as
"(333)-555-1212". The code above outputs "(###)-###-####". I'm obviously
way off here, but, I can't seem to track down a straightforward article on
how to do this. Any help would be appreciated.

Thanks
Bernie
 
P

Phillip Williams

Hi Bernie,

The syntax you tried is correct for numbers, but if your fldPhone is of type
string you would get the outcome that you got instead of the one you
expected. So to solve it, either convert it to a number before applying this
format string or use a regular expression.

For example in this line of code I remove any character that might prevent
the field from becoming a number, then convert it to a number then convert it
back again to a string using the format string that you already knew:

<asp:TextBox ID="lblPhone" runat="server" Text='<%#
Convert.ToInt64(Eval("fldPhone").ToString().Replace(" ",
"").Replace(".", "").Replace("-", "").Replace("(", "").Replace(")",
"")).ToString("000-000-0000")
%>'></asp:TextBox>

In the following line I did the same string cleaning process but then used a
regular expression to achieve the same format:

<asp:Label ID="lblPhone" runat="server"
Text='<%#FormatPhone(Eval("fldPhone").ToString()) %>'></asp:Label>

The FormatPhone function is defined as this:

protected string FormatPhone(string strPhone)
{
strPhone = Convert.ToInt64( strPhone.Replace ("
","").Replace(".","").Replace("-","").Replace ("(","").Replace
(")","")).ToString ("0000000000");
string ret= Regex.Replace(strPhone,
@"(?<AreaCode>\d{3})(?<seg1>\d{3})(?<seg2>\d{4})",
"(${AreaCode})-${seg1}-${seg2}");
return ret;
}

To understand the regular expression syntax you might review this demo on my
website in which I explained the usage of named groups in regular expressions
http://www.webswapp.com/CodeSamples/aspnet20/RegExp_NamedGroups.aspx
 
B

bernadou

Thanks once again! YTM! If you ever find yourself in Denver, I owe you a
beer!

Thanks,
B
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top