Validate a textbox in C #

4

How can I make my textbox accept only the 0 and the 1. Or only accept a character. This is the code I have.

private void press(object sender, KeyPressEventArgs e)
    {
        if (Char.IsLetter(e.KeyChar))
        {
            e.Handled = true;
        }
        if (Char.IsNumber(e.KeyChar))
        {
            e.Handled = false;
        }
    }

The one who can help me, thank you.

    
asked by use2105 22.11.2016 в 18:00
source

3 answers

2

Have you tried using regular expressions?

    private void press(object sender, KeyPressEventArgs e)
    {
        if(Regex.IsMatch(e.KeyChar.ToString(), @"[a-zA-Z01]?"))
        {                
            //TODO
        }
    }

This would allow characters from to to z in lowercase and uppercase, along with numbers 0 and 1.

    
answered by 22.11.2016 в 18:25
2

Hello you can solve it by customizing a control TextBox , I have customized a control TextBox that validates the entry of numbers, letters, decimals.

Custom TextBox-ComboBox

There you can download the sample project to see how it works, you must add the dll GlobalTech.TextBoxControl.dll as reference to the project and also to the ToolBox so you can use these controls.

    
answered by 22.11.2016 в 18:35
1

In the properties of the textbox: MaxLength = 1

 private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            //Solo aceptamos números: 0,1
            if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[0-1]"))
            {
               //Tu codigo aquí
            }else{
                 MessageBox.Show("Hey brother, por favor considera que este campo solo admite 0,1");
            }
        }
    
answered by 22.11.2016 в 18:24