How to restrict formats in c#’s textbox

Asked

Viewed 176 times

0

I’m new to programming and I have a very simple question. I am doing a practical work in college and in 4 textbox should be treated the consistencies of the notes and I wanted to restrict the textbox so that it did not accept this note format ("010"). and if the user type between 1 and 9 add a ".0" (excluding the number 10)

1 answer

1


If you only want to type numbers you can assign an event to the textbox.Keypress to handle this. Then mark the maximum size of characters 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;
    }

Good in case of validating using the Validating event of Textbox, follows below:

    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?!");
        }
    }
  • I did not want that if the user were to change to another textbox this validation would prohibit him from typing the note in this format type: note: 010

  • edited the answer, so maybe?

  • yeah, that’s what it was!

Browser other questions tagged

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