Validation of Textbox

Asked

Viewed 477 times

2

I have the following piece of code that limits a TextBox receivable only numbers and comma:

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 for all TextBox without me putting that code in the event KeyPress of each of them ?

2 answers

4


Record this method as Handler Keypress event for all Textbox:

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

Perhaps we should rename the method.

4

Another way to solve it is by creating a heritage 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 giving build, your MeuTextBox will be available in Toolbox to be used.

textbox personalizado

Browser other questions tagged

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