问题
This supposedly easy task gave me some headache. I simply want to let the user enter any text that succeeds float.TryParse
into a Textboxish control.
I could use a normal TextBox and check the Text in some btnOK_Click, but this is obviously lame. Also, there is a nice built-in MaskedTextBox control, but I failed to set it's mask to be equal to float.TryParse
. Also, it seems to check for validity only when a focus change occurs.
Digging around on the net brought some interesting ideas, but none of them as nice as I would like.
How did you solve this problem? Did I simply miss an obvious solution, or do I have to implement this functionality myself?
I'm aware of a few similar threads on SO, but there was no feasible solution to be found.
Update: Yes, WinForms.
回答1:
Edit
Well that makes it alot easier... Just add a Validating
Event Handler to your textbox
and do the TryParse
in the code behind. If its invalid, prompt the user as such.
Validating will fire when the user is finished typing and moves focus from the TextBox so if you need to do on the fly checking, you could handle the TextChanged or on of the KeyPress/KeyUp Event handlers instead
Original
Is this in asp.net or winforms/wpf
If its asp.net, you could use a combination of RegularExpressionValidator
(to account for comma seperation, 1 decimal point, etc...) and a RangeValidator
to set the min/max values for a float.
Aside from that, the only way to guarantee it would be to wrap the textbox in an updatepanel, stick a CustomServerValidator on it, and in the server validate function, do a TryParse
on the TextBox.Text
value, if it succeeds, IS VALID, if it fails, NOT VALID
回答2:
Be careful using Validating
and validating to false. You might find that, unless you enter valid data, you can't move focus off the textbox which is a really big usability pain.
I solve this by simply trying a TryParse()
on LostFocus
and if the TryParse fails I color the textbox background a reddish tint to make it obvious that something is wrong.
来源:https://stackoverflow.com/questions/828546/c-sharp-input-validation-for-a-textbox-float