vb.net 检查具有字符串值的文本框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13006153/
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
Check for Textboxes with String value
提问by Kristian Hernan C. Manuel
All I want to do is to check for textboxes with string value if yes then the message box will appear saying (use number).
我想要做的就是检查带有字符串值的文本框,如果是,那么消息框会出现说(使用数字)。
For Each t In Me.Controls
If TextBox1.Text = (String) Then
MsgBox("Please Use Number")
Exit Sub
Exit For
End If
Next
Thanks in advance
提前致谢
回答by Tim Schmelter
From your error-message i assume that you want to validate that the user entered a numerical value. Then you can either use Int32.TryParseor Double.TryParseor simply enumerate all chars and check if they are digits:
根据您的错误消息,我假设您要验证用户输入的数值。然后您可以使用Int32.TryParse或Double.TryParse简单地枚举所有字符并检查它们是否为数字:
For Each txt In Me.Controls.OfType(Of textBox)()
Dim allDigit = txt.Text.Trim.Length <> 0 AndAlso _
txt.Text.All(Function(chr) Char.IsDigit(chr))
If Not allDigit Then
MsgBox("Please Use Number")
Exit Sub
End If
Next
With Int32.TryParse:
与Int32.TryParse:
Dim intVal As Int32
Dim isInteger As Boolean = Int32.TryParse(txt.Text, intVal)
(assuming also that you want to validate all TextBoxes on your form)
(还假设您想验证表单上的所有文本框)
回答by WozzeC
Here you go:
干得好:
For Each c As Control In Me.Controls
If TypeOf (c) Is TextBox Then
If Not IsNumeric(c.Text) Then
MessageBox.Show("Not a number")
Exit Sub
End If
End If
Next
回答by Kapil Khandelwal
Use regex to validate whether or not textbox contains number.
使用正则表达式验证文本框是否包含数字。
Eg.
例如。
Dim regNumber As New Regex("^\d{1,10}$")
regNumber.IsMatch(TextBox1.Text)

