65.9K
CodeProject is changing. Read more.
Home

WinForms TextBox to accept numbers in a range

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.20/5 (2 votes)

Jan 2, 2012

CPOL
viewsIcon

12086

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.