user5368766
user5368766

Reputation:

Formatting a Textbox (Phone Numbers, Mobile Numbers, Emails)

I'd like to know how to cast textbox input into different formats. I tried using Format.String() since it's the 'solution' I found online after doing some research but it did not end well for me.

  private void RegHomePhoneTBox_TextChanged(object sender, EventArgs e)
    {
        string s = RegHomePhoneTBox.Text;
        double sAsD = double.Parse(s);
        RegHomePhoneTBox.Text = string.Format("{0:###-####}", sAsD).ToString();
    }

This was the code block I used and it just keep on throwing an error.

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll Additional information: Input string was not in a correct format.

Upvotes: 0

Views: 13745

Answers (2)

Inside Man
Inside Man

Reputation: 4372

Try this:

  private void RegHomePhoneTBox_TextChanged(object sender, EventArgs e)
    {
        string s = RegHomePhoneTBox.Text;
        if (s.Length == 7)
        {
           double sAsD = double.Parse(s);
           RegHomePhoneTBox.Text = string.Format("{0:###-####}", sAsD).ToString();
        }
        if (RegHomePhoneTBox.Text.Length > 1)
             RegHomePhoneTBox.SelectionStart = RegHomePhoneTBox.Text.Length;
        RegHomePhoneTBox.SelectionLength = 0;
    }

Upvotes: 0

Sweeper
Sweeper

Reputation: 270770

I would suggest you to use a MaskedTextBox. It works just like a regular text box but the user is forced to enter text in a specific format.

In your specific case, just set the Mask property to "000-0000".

Here's the documentation:

https://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.mask(v=vs.110).aspx

There are lots of other properties in MaskedTextBox which are very useful, like MaskCompleted.

Upvotes: 1

Related Questions