Reputation:
What is the most elegant way of restricting the input of a TextBox
control (or anything else that comes standard with .NET 3.5) to floating point numbers?
Currently, I'm doing all the heavy lifting myself by inheriting from TextBox
and overriding OnKeyPress
. However, I can't help but wonder if I'm reinventing the wheel.
Upvotes: 7
Views: 1974
Reputation: 51141
Don't forget the following issues/corner-cases that you will be facing if you go down your proposed route:
SuppressKeyPress
for everything that isn't a valid digit)"-."
, as they begin to type "-.23"
) without your textbox punishing them"-.1e-2"
could be considered legalfloat
The moral? It's can be very tricky to do what you're suggesting.
You probably either want to do a combination of the following:
TextChanged
event (and doing something passive, like changing the textbox background color) Parse
the user's value for youUpvotes: 13
Reputation: 116538
I don't think the wheel's been invented yet (at least in the .NET framework). I'm sure there's something on CodeProject or the like, doing similar to what you are though, so it may be worth a Google.
The heavy lifting shouldn't be too incredibly bad though. There is a little bit more to it than at first glance.
The overly simplified example is you can handle OnKeyPress
, do a Float.TryParse
with the new character appended in. If true, keep the keypress; if false, cancel it (e.Handled = true
).
The hard part is what if they delete, cut, or paste a selection. The other thing is when they're just starting out (you might want to accept "-" as partial valid input)...
Upvotes: 0
Reputation: 59733
I discovered the ValidatingType property of a maskedTextBox:
maskedTextBox1.ValidatingType = typeof(System.Double);
It does indeed tell you whether it's valid or not. Unfortunately, it only seems to validate when focus changes (and even then it doesn't actually do anything); but perhaps there's some way of using this.
Upvotes: 0
Reputation: 29755
Is it necessary to do the validation during data entry, or can you afford to check the final value entered once focus is lost?
If the latter, you can also use an ErrorProvider control to help restrict functionality until the input is resolved.
Upvotes: 0
Reputation: 100366
Or check for match using
void TextBox_KeyUp(object sender, KeyEventArgs e)
{
if(..) // your condition
{
e.SuppressKeyPress = false;
}
else
{
e.SuppressKeyPress = true;
}
}
or
void TextBox_KeyUp(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = CheckInput(e.KeyValue); // where CheckInput is boolean method
}
Upvotes: 0
Reputation: 1313
Take a look at the MaskedTextBox control. It also inherits from TextBoxBase and probably has the functionality you're building into yours.
Upvotes: 2