2

Hello Sorry its a simple question, but would appreciate if someone can guide me with the code. I have say 50 textboxes in my Winform. All should allow only numeric values and that too between 1-100 only. How should I ensure this validation?

My thoughts was using e.Keychar in keypress event using Ascii values to restrict users to type only numerics. Also, probably I can ensure this validation in Set in the property? But I don't know if I am correct and also don't know right code. Please help me.

1 Answer 1

5

Use NumericUpDown instead of normal TextBox box with validation.

A NumericUpDown control contains a single numeric value that can be incremented or decremented by clicking the up or down buttons of the control. The user can also enter in a value, unless the ReadOnly property is set to true.

You can specify the minimum and maximum numbers, it will allow the user to enter numbers between 1 and 100 and also let them use up and down buttons.

EDIT: If you want to do it through code then you can try something like in KeyPress event of your TextBox:

private void yourTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar)
        && !char.IsDigit(e.KeyChar))
    {
        e.Handled = true;
    }
}

The above can be improved to access . for decimal numbers, but I guess you got the idea.

Sign up to request clarification or add additional context in comments.

5 Comments

@Habib: Thanks :( I got my interview flucked :( Interviewer confused me and I just told what I wrote above :( He was again and again asking me. I never got an idea of NumericUpDOwn. Thank you Habib. But if I have to ask you how to do custom validation, any pointers for my situation please? A small code snippet would help me understand
@Divine, just updated my answer with the code, you can do that in ` KeyPress event like in the answer, it can definitely be improved, but just wanted to give you an idea
@Habib: Thank you so much. However the above code will allow values beyond 100? Or is that something that is homework for me? :) I am happy to do that if so. Well anyway, its a learning, it can be useful for my future interviews
@Divine, you can check the ascii values to see if it is between 1 and 100, you can parse it to int and see if it is between 1 and 100, many ways...., its for you to figure it out,
@Habib: Thank you so much, I will do it today itself and learn it :) :) Your input helped me a lot.... :) Cheers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.