How to restrict formats in C #

0

I'm new to programming and I have perhaps a very simple question. I'm doing a hands-on work in college and in 4 textbox the consistencies of the notes should be handled and I wanted to restrict the textbox from accepting that note format ("010"). and if the user type between 1 and 9 add a ", 0" (by taking the number 10)

    
asked by anonymous 16.02.2017 / 00:26

1 answer

1

If you want to only enter numbers you can assign an event to the textbox.KeyPress to handle this. Then mark the maximum character size to restrict the number of digits.

    public Form1()
    {
        InitializeComponent();
        textBox1.MaxLength = 2;
        textBox1.KeyPress += textBox1_KeyPress;
    }

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsNumber(e.KeyChar) && (e.KeyChar != '\b'))
            e.Handled = true;
    }

In case of validating using the Validating event of the TextBox, it follows:

    private void textBox2_Validating(object sender, CancelEventArgs e)
    {
        var tbx = (TextBox)sender;
        var txt = tbx.Text.Trim();

        //tamanho superior a tantos digitos..
        if (txt.Length > 3)
        {
            e.Cancel = true;
            MessageBox.Show("Altertar que digitou muitos digitos?!");
        }
        //algo não é número
        else if (txt.Any(w => !char.IsNumber(w)))
        {
            e.Cancel = true;
            MessageBox.Show("Altertar que digitou algo que não é número?!");
        }
        //inicia com zero e tem outros numeros
        else if (txt.StartsWith("0") && txt.Any(w => "123456789".Contains(w)))
        {
            e.Cancel = true;
            MessageBox.Show("Altertar que digitou zero antes de algum outro número?!");
        }
    }
    
16.02.2017 / 02:54