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.

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.

Thank you, thread solved.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.