5
I was practicing coding on a project like Winforms, A question soon arose: How to apply a phone mask on a Textbox. So the first thing that popped into my head was to use the event Keypress of the component.
The logic of the code became simple, follows 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 solve?
Why don’t you use a Maskedtextbox?
– Leandro Angelo
Initially the Maskedtextbox does not have format in the standard phones used in Brazil, so I believe I would have to develop a code similar to this using the Maskedtextbox
– Leonardo
@Leonardo the
MaskedTextBox
allows you to change the default mask, just put it the same way you are putting in yourString.Format
.– João Martins
@Joãomartins, but in any case would have to validate if the number is a mobile (11 digits with DDD) or fixed (10 digits with DDD), so in my view, the code will be the same as what I did using Textbox
– Leonardo
But this type of validation can only do it after the user has finished entering the text, otherwise he will not know which size, if 10 or 11. If it is not possible to notice beforehand if the number will have 10 or 11 digits, I would say that it is not possible to apply a mask...
– João Martins
I changed the event to onLeave, put a Breakpoint in the event, typed 10 numbers ... When I left the component I could see in the result of the variables that the string is not being formatted, that is, it continues with the same value...
– Leonardo