Text box to determine amount of digit usage

Asked

Viewed 69 times

1

Below follows the code I am trying to limit the use of letters in the text box, the exception of the comma, but it occurs that the comma can be typed a hundred times, I would like the comma to be used only once. How is it right?

 private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if ((e.KeyChar >= '0' && e.KeyChar <= '9') || e.KeyChar == ',')
        {
            return;
        }
        else
        {
            e.Handled = e.KeyChar != (char)Keys.Back;
        }
    }

2 answers

1

You can add one more validation

textBox1.Text.Count(letra => letra == ',') > 1

If this condition is true, the e.Handled should be true, so he wouldn’t write the comma.

Why treat the event KeyPress, know that you can still copy and paste values inside the Textbox, regardless of the character.

0

Thanks to all who will contribute, served to review my code, and I ended up changing it to:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {

        if (char.IsLetter(e.KeyChar) ) 

            e.Handled = true; 

        if (e.KeyChar == ',' && (sender as TextBox).Text.IndexOf(',') > -1)
        {
            e.Handled = true;
        }
    }

Browser other questions tagged

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