Phone and cell mask (8 or 9 digits) in the same textbox winforms

2

Good evening, I'm having trouble creating a mask that accepts both a cell phone number and phone number in the same textbox, I tried to use maskedinput but it did not roll .. any idea how I could do it? And in which event would it be best to place? (keypress, keyup, keydown, leave)

Thank you in advance for your help!

Here's a snippet of the code I've made so far using 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";
}
    
asked by anonymous 24.08.2018 / 05:31

1 answer

2

If you want to apply the mask only when focus is out of control, you can invoke 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);
}

It will return the already formatted string to apply to your TextBox .

    
24.08.2018 / 11:54