C#为Textbox输入验证:float [英] C# Input validation for a Textbox: float

查看:505
本文介绍了C#为Textbox输入验证:float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个简单的任务给了我一些头痛的问题。我只是想让用户输入任何成功 float.TryParse 的文本到Textboxish控件中。



我可以使用正常的文本框,并检查文本中的一些btnOK_Click,但这显然是跛脚。此外,还有一个很好的内置MaskedTextBox控件,但是我没有将其掩码设置为等于 float.TryParse 。此外,它似乎只有当焦点变化发生时检查有效性。



在网络上挖掘带来了一些有趣的想法,但没有一个像我想要的那么好。



你是如何解决这个问题的?我只是错过了一个明显的解决方案,或者我必须自己实现这个功能?

我知道一些类似的线程在SO上,但没有可行的解决方案被发现。

更新:是,WinForms。

解决方案 编辑

好吧,这使得它更容易...只需添加一个验证事件处理程序到您的文本框
,并在后面的代码中执行 TryParse 。如果无效,则提示用户。



验证将在用户完成键入并从TextBox移动焦点时触发,因此如果您需要在飞行检查,您可以处理TextChanged或KeyPress / KeyUp事件处理程序而不是

原始
$ b $如果是asp.net,你可以使用 RegularExpressionValidator 的组合, code>(以逗号分隔,小数点后一位等等)和一个 RangeValidator 来设置一个浮点数的最小值/最大值。 p>

除此之外,保证它的唯一方法是将文本框包装到一个updatepanel中,将一个CustomServerValidator放在它上面,并在服务器验证函数中执行> TryParse ,如果成功,则为有效,如果失败,则为有效

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.

解决方案

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

这篇关于C#为Textbox输入验证:float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆