Search code examples
c#string-formattingmaskphone-number

Format text different way if TextLength = 13 using keypress


i have code to format telephone number automatically, format is 12 3456-7890

1234567890 = 12 3456-7890 (TextLength = 12)

I want if TextLength = 13 format this way

12345678901 = 12 34567-8901 (TextLength = 12) or in another words, change postion of "-" to 1 position right and add last number on last character

my actual code

private void txtFonecom_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)Keys.Back)
    {
    }
    else
    {
        if (txtFonecom.TextLength == 2)
        {
            txtFonecom.Text = txtFonecom.Text + " ";
            txtFonecom.SelectionStart = 3;
            txtFonecom.SelectionLength = 0;
        }
        if (txtFonecom.TextLength == 7)
        {
            txtFonecom.Text = txtFonecom.Text + "-";
            txtFonecom.SelectionStart = 8;
            txtFonecom.SelectionLength = 0;
        }
        if (txtFonecom.TextLength == 13)
        {
            //here i have to change format from 12 3456-7890 to 12 34567-8901
        }
    }
}

Solution

  • Instead of manually handling the keypresses I would suggest using the MaskedTextBox control with the mask 00 0000-0000 since the control can automatically format the input for you.

    Assuming you still prefer to go for a TextBox solution here is the solution:

    private void txtFonecom_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)Keys.Back)
        {
        }
        else
        {
            if (txtFonecom.TextLength == 2)
            {
                txtFonecom.Text = txtFonecom.Text + " ";
                txtFonecom.SelectionStart = 3;
                txtFonecom.SelectionLength = 0;
            }
            if (txtFonecom.TextLength == 7)
            {
                txtFonecom.Text = txtFonecom.Text + "-";
                txtFonecom.SelectionStart = 8;
                txtFonecom.SelectionLength = 0;
            }
            if (txtFonecom.TextLength == 12)
            {
                int caretPos = txtFonecom.SelectionStart;
                txtFonecom.Text = txtFonecom.Text.Replace("-", string.Empty).Insert(8, "-");
                txtFonecom.SelectionStart = caretPos;
            }
        }
    }
    

    Keep in mind you will need to handle the format when the user deletes numbers.