限制用户输入只在C#Windows应用程序的数字 [英] Restricting users to input only numbers in C# windows application

查看:142
本文介绍了限制用户输入只在C#Windows应用程序的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾尝试这个代码只限制numbers.It只输入数字,不要使条目时,我们尝试输入字符或任何其他控件,即使它不也进入退格。如何防止退格如此。

 私人无效TxtBox1_KeyPress(对象发件人,KeyPressEventArgs E)
{
如果
e.Handled =真(System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(),\\d +)!);
}


解决方案

您不需要使用为了一个正则表达式来测试数字:

 私人无效TxtBox1_KeyPress(对象发件人,KeyPressEventArgs E)
{
如果(Char.IsDigit(e.KeyChar)!)
e.Handled = TRUE;
}

要允许退格键:

 私人无效TxtBox1_KeyPress(对象发件人,KeyPressEventArgs E)
{
如果(!(Char.IsDigit(e.KeyChar)||(e.KeyChar ==(char)的Keys.Back)))
e.Handled = TRUE;
}

如果您要添加其他许可密钥,看的 枚举和使用上面的方法。


I have tried this code to restrict only numbers.It type only numbers and don't make entry when we try to enter characters or any other controls, even it doesnt enter backspace also. how to prevent backspace from it.

private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
{
     if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+"))
          e.Handled = true;
}

解决方案

You do not need to use a RegEx in order to test for digits:

private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
{
     if (!Char.IsDigit(e.KeyChar))
          e.Handled = true;
}

To allow for backspace:

private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
{
     if (!(Char.IsDigit(e.KeyChar) || (e.KeyChar == (char)Keys.Back)))
          e.Handled = true;
}

If you want to add other allowable keys, look at the Keys enumeration and use the approach above.

这篇关于限制用户输入只在C#Windows应用程序的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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