Mask for phone and mobile phone (8 or 9 digits) in the same textbox winforms

Asked

Viewed 3,378 times

2

Good evening, I’m having trouble creating a mask that accepts both cell phone number and phone number in the same textbox, I tried to use the maskedinput no more rolled.. Any idea how you could do it? And what event would be best to put it in? (keypress, keyup, keydown, Leave)

Thank you in advance for your help!

There’s an excerpt of the code I’ve made so far using the maskedinput..

String telefone = Useful_methods.TextNoFormatting(txtTelefone_1);
if (telefone.Length >= 10)
{
   txtTelefone_1.Mask = "(00)00000-0000";
   txtTelefone_1.Select(txtTelefone_1.Text.Length, 1);
}
else
{
   txtTelefone_1.Mask = "(00)0000-00009";
}
  • You want the format to be validated while the user enters the number or it can be in the event of LostFocus?

  • can be in Lostfocus

1 answer

3


If you want to apply the mask only when the focus out of control, can evoke this method:

string AplicarMascaraTelefone(string strNumero)
{
    // por omissão tem 10 ou menos dígitos
    string strMascara = "{0:(00)0000-0000}";
    // converter o texto em número
    long lngNumero = Convert.ToInt64(strNumero);

    if (strNumero.Length == 11)
        strMascara = "{0:(00)00000-0000}";

    return string.Format(strMascara, lngNumero);
}

Will return the already formatted string to apply to your TextBox.

Browser other questions tagged

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