Nov 18, 2011

NumericTextBox (C#.NET): A TextBox for numbers with built-in mathematical expression evaluation

The article was updated to the version 1.2. The links are already pointing to the new versions of the files. See details below. 

In my project I had a TextBox on one of the forms for entering quantity, and I thought it would be a cool feature if it could understand such basic expressions as 10+42 or 4*8 and so on...
So decided to create a new Control derived from the TextBox, because this could be useful in the future, and now I'm sharing my result.

First of all, since I decided to create a new control, I wanted to make it as flexible as possible, so the expressions that can be understood by the control can include the four basic operations (+, -, *, /) and parentheses, in any valid combination (spaces can be used, they will be skipped).
e.g.: 40+2 or (12+3/ 4) * 4-3*3 or 10+2*(2+5* (4-(2-0.5))+1.5)

Second, I added some extra functionality to the TextBox some are taken from NumericUpDown control, but there are some which I used already but now I built them in the control (changing background color based on value).