Text box to determine amount of digit usage

1

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

 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;
        }
    }
    
asked by anonymous 17.12.2017 / 14:52

2 answers

1

You can add another validation

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

If this condition is true, e.Handled should be true , so that it does not write the comma.

By treating the event KeyPress , you can still copy and paste values within the TextBox, regardless of the character.

    
17.12.2017 / 15:25
0

Thanks to all who will contribute, they 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;
        }
    }
    
31.12.2017 / 20:29