vb.net 如何使文本框只接受数字字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5814639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a text-box accept only numeric characters?
提问by Failed_Noob
How to make a text-box accept only numeric characters (0-9) ? and give an error Message if it contains any alphabets or symbols.
如何使文本框只接受数字字符 (0-9) ?如果它包含任何字母或符号,并给出错误消息。
回答by Marco
You could catch the event KeyDown
and check if e.KeyCode
is numeric or not and discard it if you want.
Another thing you could try is using IsNumeric(txt.Text)
.
您可以捕获该事件KeyDown
并检查是否e.KeyCode
为数字,并根据需要丢弃它。
您可以尝试的另一件事是使用IsNumeric(txt.Text)
.
回答by Naveed
回答by Erin Packard
You could use a Regular Expression something like: ^(\d{0,11})(.\d{0,2})?$ This will allow 0-11 digits left of the decimal and 0-2 digits right of the decimal.
您可以使用类似于以下内容的正则表达式: ^(\d{0,11})(.\d{0,2})?$ 这将允许小数点左侧 0-11 位数和小数点右侧 0-2 位数十进制。
If you have Ajax Controls you could use a Filtered Textbox Extender
<cc1:FilteredTextBoxExtender id="FilteredTextBoxExtender8" runat="server" TargetControlID="YourTextBox" FilterType="Custom,Numbers" ValidChars="." >
</cc1:FilteredTextBoxExtender>
如果您有 Ajax 控件,则可以使用 Filtered Textbox Extender
<cc1:FilteredTextBoxExtender id="FilteredTextBoxExtender8" runat="server" TargetControlID="YourTextBox" FilterType="Custom,Numbers" ValidChars="." >
</cc1:FilteredTextBoxExtender>
Or you could also try Marco's approach.
或者您也可以尝试 Marco 的方法。
回答by Developer
How about this will allow only numeric data and Back space
怎么样这将只允许数字数据和退格
Under Keypress
event
在Keypress
事件
if ((!char.IsNumber(e.KeyChar)) && !(e.KeyChar == (char)Keys.Back))
{
e.Handled = true;
}
回答by akkireddy
Here i am with pincode textbox name an pin code and ID as txtPinCode
在这里,我使用密码文本框将密码和 ID 命名为 txtPinCode
you just write on top of the code under document function starts lets write this code and check once
您只需在文档功能开始下的代码之上编写让我们编写此代码并检查一次
$("#<%=txtPincode.ClientID%>").numeric();
$("#<%=txtPincode.ClientID%>").numeric();
thanks akreddy
谢谢阿克雷迪
回答by Jakir Hossain
If Asc(e.KeyChar) <> 13 AndAlso Asc(e.KeyChar) <> 8 AndAlso Not IsNumeric(e.KeyChar) Then
MessageBox.Show("Please enter numbers only")
e.Handled = True
End If