Format the Phone Number in asp.net using c#

In this tutorial you will learn how to format the phone number entered in a textbox. Phone number can be entered in a textbox as 1234567890 but you can format it as (123)456-789 and this is our topic.

Let's have a look how to do so.


Format the Phone Number in asp.net using c#

Let's suppose we have an asp:textbox in our .aspx page in which user will enter the phone number. The id of asp:textbox is txtPhoneNumber.

public string PhoneNoFormation()
{
string formatedPhoneNo;
if (!string.IsNullOrEmpty(txtPhoneNumber.Text.ToString()) && txtPhoneNumber.Text.Length == 10)
{
string Phone1 = "(" + txtPhoneNumber. Text.Substring(0, 3) + ")";
string Phone2 = " " + txtPhoneNumber. Text.Substring(3, 3);
string Phone3 = "-" + txtPhoneNumber. Text.Substring(6, 4);
formatedPhoneNo = Phone1 + Phone2 + Phone3;
}

else
{
formatedPhoneNo = txtPhoneNumber.Text;
}

return formatedPhoneNo;
}

Now your phone number is in formatted form and you can save it in database if you want to do so.

So that's it. I hope you will find this tutorial very informative.

I love your feedback.

0 comments: