如何验证Windows表单 [英] How to validate a windows form

查看:51
本文介绍了如何验证Windows表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何验证我的表单,使其仅在文本框中输入字符值?

How to validate my form so that it enter only character value in textbox?

推荐答案

可能,最好的方法是不要进行表单验证这,但是要处理提交的字符.
如果您一开始就阻止用户输入无效字符,则无需在消息框中打断用户的工作流程.

有两种处理方法:通过TextBox.KeyPress事件并使用e.KeyChar值来限制他可以输入的值,或者使用TextBox.TextChanged事件来防止输入任何无效字符.后者更安全,因为它涵盖粘贴的数据和类型化的数据,但实现起来稍微复杂一些.

例如:
Probably, the best thing to do is not to do form validation to do this, but to handle the characters as they are submitted instead.
If you prevent the user from entering invalid characters in the first place, then you don''t need to interrupt his work flow with a message box.

There are two ways to handle it: via the TextBox.KeyPress event and use the e.KeyChar value to restrict the values that he can enter, or use the TextBox.TextChanged event to prevent any entry of invalid characters. The later is more secure in that it covers pasted data as well as typed, but a little more complex to implement.

For example:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
    if (e.KeyChar >= '0' && e.KeyChar <= '9') e.Handled = true;
    }

将阻止TextBox接受数字键.

还有MaskedTextBox,它可以通过多种方式限制输入.

Will prevent the TextBox from accepting numeric keys.

There is also the MaskedTextBox which can restrict the input in many ways.


^ ]


这篇关于如何验证Windows表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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