[英]How to only allow the numbers ,backspace key and hypen key to be pressed on textbox
I made a textbox to to insert a phone number .我做了一个文本框来插入电话号码。 I only want numbers, delete button and hyphen key to be pressed.
我只想按下数字、删除按钮和连字符键。 I used following code : It works for delete button and numbers , what shoud I do for hyphen?
我使用了以下代码:它适用于删除按钮和数字,我应该为连字符做什么?
private void ContactNumTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
const char Hyphen = (char)2d;
const char Delete = (char)8;
if (char.IsNumber(e.KeyChar) && e.KeyChar != Hyphen && e.KeyChar!= Delete)
e.Handled = true;
}
When using hex numbers, you must prefix the number with 0x
.使用十六进制数字时,必须在数字前面加上
0x
。 Your code currently compiles due to the coincidence that d
specifies the number is a double.由于
d
指定数字是双精度数的巧合,您的代码当前可以编译。 The following code will correctly detect hyphens:以下代码将正确检测连字符:
private void ContactNumTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
const char hyphen = (char)0x2D;
const char delete = (char)0x08;
if (!char.IsNumber(e.KeyChar) && e.KeyChar != hyphen && e.KeyChar!= delete)
e.Handled = true;
}
you can also try this one你也可以试试这个
if (!(char.IsDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == '-'))
{
e.Handled = true;
}
You can try to write this code in KeyPress event:您可以尝试在 KeyPress 事件中编写此代码:
private void txtTextBoxName_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !Char.IsNumber(e.KeyChar) && e.KeyChar != 8;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.