I need to insert phone number and mobile number in the same textbox using masks in Windows form C#

Asked

Viewed 37 times

-1

Type I wanted to know if there is any way to create a format whenever the user type some characters (ex: 8 for phone and 9 for mobile), already identify and apply in the textbox. Or when the user enters a specific character already identify that is the phone or mobile number (ex: when entering the number 9 already identify and apply the format to mobile). Or some other way to apply the 2 in a single textbox.

below is a code I made for phone in case it is useful.

private void Tel(object sender, KeyPressEventArgs e)
        {
            if (char.IsDigit(e.KeyChar) || e.KeyChar == (char)(Keys.Back))
            {
                e.Handled = false;                
                if (e.KeyChar == (char)(Keys.Back))
                {
                    txtTel.Text = "";
                }
                if (txtTel.Text.Length == 0)
                {
                    txtTel.Text += "(";
                }

                if (txtTel.Text.Length == 6)
                {
                    txtTel.Text += ")";
                }

                if (txtTel.Text.Length == 2)
                {
                    txtTel.Text += "X";
                }

                if (txtTel.Text.Length == 3)
                {
                    txtTel.Text += "X";
                }

               if (txtTel.Text.Length == 11)
                {
                    txtTel.Text += "-";
                }
            }

            else
            {
                e.Handled = true;
            }
            txtTel.SelectionStart = txtTel.TextLength + 1;

1 answer

0

The best option is to use a type control Maskedtextbox instead of Textbox. It will already include the mask in the phone format for example (XX) XXXX-XXXX.

After changing control to Maskedtextbox, add an event handler to Textchanged in it:

private void maskedTextBox1_TextChanged(object sender, EventArgs e)
{
    if ("9".Equals(maskedTextBox1.Text.Substring(5, 1)))
    {
        maskedTextBox1.Mask = "(99) 99999-9999";
    }
    else
    {
        maskedTextBox1.Mask = "(99) 9999-9999";
    }
}

In my example, it only includes a logic of adding 1 digit when after the DDD comes a number 9.

If you want to take action when the mask is rejected, add an event handler for the Maskinputrejected event. Note that in my case, I clear the field if the mask is filled incorrectly.

private void maskedTextBox1_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
{
    if (maskedTextBox1.Text.Length != maskedTextBox1.Mask.Length)
        maskedTextBox1.ResetText();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.