vb.net 检查文本框输入是否为数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15423114/
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
Checking to see if text box input is numeric
提问by Matt
I've done some research on this and still cannot get my program to work. I simply need to check the text box to see if the user input is a numeric value, or not (with the exception of a "." and or "/")
我已经对此进行了一些研究,但仍然无法使我的程序正常工作。我只需要检查文本框以查看用户输入是否为数值(“.”和或“/”除外)
My code so far,
到目前为止,我的代码
Private Sub Num1_KeyPress(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Num1.KeyPress
Dim UserEntry As Boolean
If UserEntry = IsNumeric(False) Then
MessageBox.Show("That's not numeric!")
End If
End Sub
回答by Trevor
I recommend handling TextChanged and checking the whole number instead of a single character.
我建议处理 TextChanged 并检查整数而不是单个字符。
Private Sub Num1_TextChanged(sender As Object, e As TextChangedEventArgs) Handles Num1.TextChanged
If IsInputNumeric(Num1.Text) Then
'handle numeric input
Else
'handle not a number
End If
End Sub
Private Function IsInputNumeric(input As String) As Boolean
If String.IsNullOrWhiteSpace(input) Then Return False
If IsNumeric(input) Then Return True
Dim parts() As String = input.Split("/"c)
If parts.Length <> 2 Then Return False
Return IsNumeric(parts(0)) AndAlso IsNumeric(parts(1))
End Function
回答by Abdusalam Ben Haj
I think you better be using TextBox.KeyUp
event, it passes the KeyEventArgs
. Try this :
我认为您最好使用TextBox.KeyUp
事件,它通过KeyEventArgs
. 尝试这个 :
Private Sub Num1_KeyUp(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles Num1.KeyUp
Dim isDigit As Boolean = Char.IsDigit(ChrW(e.KeyValue))
Dim isKeypadNum As Boolean = e.KeyCode >= Keys.NumPad0 And e.KeyCode <= Keys.NumPad9
Dim isBackOrSlashOrPeriod As Boolean = (e.KeyCode = Keys.Decimal Or e.KeyCode = Keys.Oem2 Or e.KeyCode = Keys.Back Or e.KeyCode = Keys.OemPeriod)
If Not (isDigit Or isKeypadNum Or isBackOrSlashOrPeriod) Then
MessageBox.Show("That's not numeric!")
End If
End Sub
回答by Esselans
Public Function onlyNumbers(ByVal KeyChar As Char) As Boolean
Dim allowedChars As String
allowedChars = "0123456789./"
If allowedChars.IndexOf(KeyChar) = -1 And (Asc(KeyChar)) <> 8 Then
Return True
End If
Return False
End Function
true means an invalid char.
true 表示无效字符。
On keypress you need to do:
在按键时,您需要执行以下操作:
e.handled = onlyNumbers(e.keychar)
回答by DeanOC
I find that this sort of validation is much easier to do either in the textBox's LostFocus
eventHandler, or at the Form level, e.g. when the user clicks the OK button.
我发现这种验证在 textBox 的LostFocus
eventHandler 中或在 Form 级别(例如,当用户单击 OK 按钮时)更容易进行。
Then you can do your validation as follows
然后你可以做你的验证如下
a)Does the textbox contain any chars outside of "0123456789./"
If so then non-numeric
a)文本框是否包含"0123456789./"
If so then non-numeric之外的任何字符
b)Split the text wherever the "/"
character appears (if any), and then use the IsNumeric()
function on each substring. If any of them are not numeric, then the text is not numeric.
b)在"/"
字符出现的地方(如果有)拆分文本,然后IsNumeric()
在每个子字符串上使用该函数。如果其中任何一个不是数字,则文本不是数字。
This does assume that you are allowing 1/2/2, .i.e. 1/4. If not then you also have to check that there is a max of 1 "/" chars in your string.
这确实假设您允许 1/2/2,即 1/4。如果没有,那么您还必须检查字符串中是否最多有 1 个“/”字符。
回答by Cesar Alpendre
Private Sub tbYear_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tbYear.KeyPress
If e.KeyChar < Chr(48) Or e.KeyChar > Chr(57) Then
e.KeyChar = Nothing
End If
End Sub
回答by Fake Faker
' Validates textboxes for numeric only keystrokes. Hook this up to the
' PreviewTextInput of the desired textbox
Private Sub SetTextboxNumericOnly(sender As Object,
e As TextCompositionEventArgs)
Dim regex As New System.Text.RegularExpressions.Regex("[^0-9]+")
e.Handled = regex.IsMatch(e.Text)
End Sub
Keep in mind that you still need to check if the textbox contains a value in case they delete the contents of the textbox. This routine ensures it is always numeric and so there is no longer a need to check.
请记住,您仍然需要检查文本框是否包含值,以防它们删除文本框的内容。此例程确保它始终是数字,因此不再需要检查。
回答by rbassett
On a slight tangent, according to the top answer to the question checking for numeric value entered in text box in visual basic, there is also the method .TryParsewhich is considered a better solution than IsNumeric :
稍微切切一点,根据在visual basic中检查文本框中输入的数值的问题的最佳答案,还有方法.TryParse被认为是比 IsNumeric 更好的解决方案:
The first reason is that with TryParse you also get the result of the conversion while with IsNumeric you would have to do the conversion after the check.
The second reason is that you could give to IsNumeric whatever object you want (also a Button for example) and it accepts it. You would never discover this kind of errors at compile time. Instead, with TryParse, you could only pass a string as its first parameter.
第一个原因是使用 TryParse 您还可以获得转换结果,而使用 IsNumeric 您必须在检查后进行转换。
第二个原因是你可以给 IsNumeric 任何你想要的对象(例如一个 Button)并且它接受它。您永远不会在编译时发现此类错误。相反,使用 TryParse,您只能传递一个字符串作为其第一个参数。