Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WinForms

WinForms TextBox to accept numbers in a range

4.20/5 (2 votes)
2 Jan 2012CPOL 12K  
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)