Validating TextBox

2

I have the following code snippet that limits a TextBox to receive only numbers and commas:

private void txtTempoAcel1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!Char.IsDigit(e.KeyChar) && e.KeyChar != (char)8 && e.KeyChar == 48)
        e.Handled = true;
}

But I have several TextBox and would like to replicate this code for everyone. Is there any way I can replicate this validation to all TextBox without putting this code in the KeyPress event of each of them?

    
asked by anonymous 23.01.2017 / 15:05

2 answers

4

Register this method as handler of the KeyPress event for all TextBox:

textBox1.KeyPress += txtTempoAcel1_KeyPress;
textBox2.KeyPress += txtTempoAcel1_KeyPress;
textBox3.KeyPress += txtTempoAcel1_KeyPress;
textBox4.KeyPress += txtTempoAcel1_KeyPress;
...
...

It may be convenient to give the method another name.

    
23.01.2017 / 15:27
3

Another way to solve this is to create a inheritance of TextBox

public class MeuTextBox : TextBox
{
    private bool _validaDigito;

    public MeuTextBox()
    {
        ValidaDigito = true;
    }

    public bool ValidaDigito
    {
        get { return _validaDigito; }
        set
        {
            _validaDigito = value;

            if (value)
                KeyPress += Text_KeyPress;
            else
                KeyPress -= Text_KeyPress;
        }
    }

    private void Text_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!Char.IsDigit(e.KeyChar) && e.KeyChar != (char)8 && e.KeyChar == 48)
            e.Handled = true;
    }
}

When building, your MeuTextBox will be available in the ToolBox to be used.

    
23.01.2017 / 18:10