Mask for Formatting TextBox

5

I was practicing programming in a WinForms project, so a question arose: How to apply a phone mask to a TextBox . So the first thing that came to mind was to use the KeyPress event of the component.

The logic of the code was simple, below ...

private void cbTelefone_KeyPress(object sender, KeyPressEventArgs e)
    {
        string numero = Convert.ToString(cbTelefone.Text);

        if (numero.Length <= 10) // Telefone Fixo com DDD
        {
            string numeroTelefoneFixo = Convert.ToString(cbTelefone.Text);
            cbTelefone.Text = String.Format(@"{0:(00)0000-0000}", numeroTelefoneFixo);
        }
        else if (numero.Length == 11) // Celular com DDD
        {
            string numeroTelefoneCelular = Convert.ToString(cbTelefone.Text);
            cbTelefone.Text = String.Format(@"{0:(00)00000-0000}", numeroTelefoneCelular);
        }

The TextBox is not receiving the phone mask. What should I do to fix it?

    
asked by anonymous 22.08.2018 / 18:24

1 answer

1

The problem will be that String.Format can not convert a String to a numeric format.

Try converting the phone number from TextBox to a number and then apply the mask:

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);
}

Note that this method should only be called in Leave , it will not work correctly in KeyPress , as we have already discussed in the comments of your question.

    
23.08.2018 / 10:31