Click here to Skip to main content
15,880,503 members
Articles / Desktop Programming / Windows Forms
Alternative
Tip/Trick

WinForms TextBox to accept numbers in a range

Rate me:
Please Sign up or sign in to vote.
4.20/5 (2 votes)
2 Jan 2012CPOL 11.6K   1
A few notes on this code: Wouldn't you get an exception if the user happens to put in a number bigger than can be stored in an int32? Wouldn't int32.TryParse be better because of this?The control can be initialized with a negative number as a constraint, but it doesn't permit the '-'...
A few notes on this code:

Wouldn't you get an exception if the user happens to put in a number bigger than can be stored in an int32? Wouldn't int32.TryParse be better because of this?

The control can be initialized with a negative number as a constraint, but it doesn't permit the '-' character to be entered.

What happens when the min > max? I'd expect the code to handle that somehow. Choices could be to just take two numbers and figure out which is smaller and use that as the min, throw an exception, or take a min and a range size in the constructor.

I'm not sure why you chose to create event handlers for this when you've derived from TextBox. Wouldn't it be more straightforward to override OnKeyDown, OnTextChanged, and OnLeave?

Also, as someone else said, you really should leave the default constructor in place so that this can be used with the WinForms designer. Min and Max should be exposed as properties, so that they can be set in the designer or in code. You can attribute them to appear in the correct section in the property pane.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Product Manager
United States United States
I've been programming in C, C++, Visual Basic and C# for over 35 years. I've worked at Sierra Systems, ViewStar, Mosaix, Lucent, Avaya, Avinon, Apptero, Serena and now Guidewire Software in various roles over my career.

Comments and Discussions

 
GeneralReason for my vote of 4 Thanks for your feedback. Implemente... Pin
Manish K. Agarwal2-Jan-12 23:03
Manish K. Agarwal2-Jan-12 23:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.