0

I need a textBox that accepts only numerical values ranging from 1 to 10 for my application. Can you assist me please? Take a look at my code (it only does half the job since text inserted from the clipboard using the standard right-click menu strip of the textBox will still appear + haven't implemented value restricting functionality).

My textBox KeyPress event:

private void tbTimes_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(char.IsDigit(e.KeyChar) || e.KeyChar == Convert.ToChar(Keys.Back)
                || e.KeyChar == Convert.ToChar(Keys.Enter)))
            {
                e.Handled = true;
            }
            else
            {
                // Will implement functionality later
            }
        }

My textBox TextChanged event:

private void tbTimes_TextChanged(object sender, EventArgs e)
        {
            // I guess restricting the values to 1 to 10 would go here
            // but I don't know how I would go about doing it, exactly.
        }

Please help me. Thanks in advance.

Edited by TechSupportGeek

2
Contributors
2
Replies
19
Views
4 Years
Discussion Span
Last Post by TechSupportGeek
0

You could try handling the Validated event. You have the option to cancel the validation so that the user's focus stays on the textbox until the value is valid. Using the Integer.TryParse then checking the value, is an easy way to validate the text.

Alternatively using a NumericUpDown control will restrict the input to exactly what you need. The user can type the number or use the scroll buttons to set the value.

Edited by tinstaafl

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.