验证文本框(仅数字或字母除外) [英] Validating Textbox(only except numbers or letters)

查看:82
本文介绍了验证文本框(仅数字或字母除外)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

验证文本框以使文本框只能除数字之外的最简单方法是什么?还有一个仅包含字母的文本框?

What''s the easiest way to validate a textbox so that the textbox can only except numbers? And an other textbox only except letters?

推荐答案

文本框上的按键事件

Keypress event on the textbox

private void txtSimnr_KeyPress(object sender, KeyPressEventArgs e)
        {
       if (!char.IsControl(e.KeyChar)
       && !char.IsDigit(e.KeyChar)
       && e.KeyChar != '.')
            {
                e.Handled = true;
            }

        }


以下是一些替代方案

1.使用MaskedTextBox(这是最简单的方法),在此处说明
http://msdn.microsoft.com/en-us/library/system. windows.forms.maskedtextbox.aspx [ ^ ]
2.在KeyPress事件中,如果按下的键不是必需的字符,则设置e.Handled = true
3.在KeyDown事件中,如果按下的键不是必需的字符,则设置
e.SuppressKeyPress = true
The following are some of the alternatives

1. Use MaskedTextBox (this is easiest approach) explained here
http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx[^]
2. In the KeyPress event if the Key pressed is not the required character then set e.Handled = true
3. In the KeyDown event if the key pressed is not the required character then set
e.SuppressKeyPress = true


这篇关于验证文本框(仅数字或字母除外)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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