Wednesday, April 10, 2013

Format Phone Numbers in US (United States Phone Number format) in asp.net

You can give any style to phone number or any other texual content. Use String.Format.
You can also apply check on phone number if already dash is used then no repeat of dash in phone number
 string PhoneNumber=  Convert.ToString(DataBinder.Eval(e.Item.DataItem, "Phone"));

 if (!phoneNumber.Contains("-"))
{
lblPhoneNumber.Text  = string.Format("{0}-{1}-{2}", PhoneNumber.Substring(0, 3), PhoneNumber.Substring(3, 3), PhoneNumber.Substring(6));
}
else
lblPhoneNumber.Text = PhoneNumber;

Then Phone number will display like 123-456-7890
To make format like (123) 456-7890 use
You can also use this format in   "({0}) {1}-{2}"