Search code examples
c#winformsintegerrangemaskedtextbox

How To Limit a masked textbox to only accept an integer between 0-11, C#?


OK, so I've been searching all over for the answer, and truthfully think I'm just googling the wrong thing. Anyway, I'm using Visual Studio 2012 and making a simple winform, BMI Calculator. I have a masked text box for the user to enter inches. Currently the box is set to only accept an integer one or two digits long, but I'd also like to make this text-box only allow the user to enter a number between 0-11. Any help on how to do this would be great. The box looks like this:

    private void heightInches_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
    {

    }

I do have the text box parsed and assign the input to a variable:

    inches = int.Parse(heightInches.Text);

And to make sure the input can't be left blank I'm using this:

 if (string.IsNullOrWhiteSpace(heightInches.Text))
            {
                MessageBox.Show("Please Enter An Input For Inches.");

                return; 
            }

Solution

  • The easiest solution would be to use a NumericUpDown, and set the Minimum to 0 and the Maximum to 11. This would also have the added benefit of allowing the user to use either the mouse or UpArrow and DownArrow as well as 0-9 to enter values.