vb.net 检查在 Visual Basic 中的文本框中输入的数值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21894851/
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 for numeric value entered in text box in Visual Basic
提问by Steve
I am working on a program for my Visual Basic class and have a quick question. One of the things we were encouraged to do was to check to make sure the quantity entered in a text box is actually a number. Our professor suggested using IsNumeric to perform this check, but I'm running into some trouble. I already had a good bit of the code written before he added this to the instructions, so not sure how to integrate this into the code I already have.
我正在为我的 Visual Basic 课程编写一个程序,并有一个简单的问题。我们被鼓励做的一件事是检查以确保在文本框中输入的数量实际上是一个数字。我们的教授建议使用 IsNumeric 执行此检查,但我遇到了一些麻烦。在他将其添加到说明中之前,我已经编写了大量代码,因此不确定如何将其集成到我已有的代码中。
The main purpose of the program is to allow the user to add ingredients from one list box to the recipe list box, input a quantity for each selected ingredient in a text box, and calculate the total calories for the recipe. The way I have the code written now, IsNumeric is part of a nested if statement at the beginning of where I will start adding the selected ingredients to the recipe list box. I'm not sure if that's the correct place for it though.
该程序的主要目的是允许用户将一个列表框中的成分添加到食谱列表框中,在文本框中输入每个选定成分的数量,并计算该食谱的总卡路里。按照我现在编写代码的方式,IsNumeric 是嵌套 if 语句的一部分,位于我将开始将所选成分添加到配方列表框的开头。我不确定这是否是它的正确位置。
Here is the code I have written so far.
这是我到目前为止编写的代码。
Public Class Form1
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim i As Integer = lstIngredients.SelectedIndex
Dim Quantity As Double
Dim intCount As Integer = 0
If Trim(txtQuantity.Text = "") Then
Quantity = 1
Else
Quantity = Me.txtQuantity.Text
End If
If txtQuantity.Text Is IsNumeric() Then
If intCount < Quantity Then
lstRecipe.Items.Add(Quantity & " " & lstIngredients.Text)
intCount += 1
End If
Else
MessageBox.Show("The quantity entered is not numeric. Please add a numeric quantity.")
End If
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
lstRecipe.Items.Clear()
txtQuantity.Clear()
txtAnswer.Clear()
End Sub
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
End Sub
End Class
Also, here is the error I receive when I attempt to run this program as it is written.
此外,这是当我尝试在编写时运行该程序时收到的错误。
Error 1 Argument not specified for parameter 'Expression' of 'Public Function IsNumeric(Expression As Object) As Boolean'.
Any suggestions would be greatly appreciated.
任何建议将不胜感激。
回答by Steve
A more correct way to do that is to use the TryParse
method available in the Int32
or Double
class
更正确的方法是使用or类中TryParse
可用的方法Int32
Double
If Double.TryParse(txtQuantity.Text, Quantity) Then
If intCount < Quantity Then
lstRecipe.Items.Add(Quantity & " " & lstIngredients.Text)
intCount += 1
End If
Else
MessageBox.Show("The quantity entered is not numeric. Please add a numeric quantity.")
End If
And you could also remove the code that test for the empty textbox.
您还可以删除测试空文本框的代码。
The TryParse
method wants two parameters, the first one is the string that could be converted, the second parameter is the variable that receives the result of the conversion if it is possible. If the conversion cannot be executed the function returns false.
该TryParse
方法需要两个参数,第一个是可以转换的字符串,第二个参数是可能的话接收转换结果的变量。如果无法执行转换,则该函数返回 false。
There are numerous reasons to prefer Double.TryParseinstead of IsNumeric
.
有很多理由更喜欢Double.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.
第一个原因是,withTryParse
你也得到了转换的结果,而withIsNumeric
你必须在检查后进行转换。
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.
第二个原因是你可以给IsNumeric
任何你想要的对象(例如一个 Button)并且它接受它。您永远不会在编译时发现此类错误。相反,使用TryParse
,您只能传递一个字符串作为其第一个参数。
回答by bd33
You're just using the function incorrectly - you need to pass the string as a parameter.
您只是错误地使用了该函数 - 您需要将字符串作为参数传递。
If IsNumeric(txtQuantity.Text) Then
回答by trparky
Use Regex.IsMatch:
Public Function isNumeric(input As String) As Boolean
Return Regex.IsMatch(input.Trim, "\A-{0,1}[0-9.]*\Z")
End Function
回答by Rick FlyFish
Private Sub txbDwellTime_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txbDwellTime.KeyPress
numDecOnly(e)
End Sub
Public Sub numDecOnly(ByVal e As System.Windows.Forms.KeyPressEventArgs)
If (Asc(e.KeyChar) >= 48 And Asc(e.KeyChar) <= 57 Or Asc(e.KeyChar) = 46) Then
'good job do nothing we only allow positive Decimal numbers in this field
'Asc(e.KeyChar) 48 Through 57 i.e. 0 through 9 Or Asc(e.KeyChar) 46 (dot= .)
Else
e.Handled = True
MsgBox("Only Positive Decimal Numbers Allowed this field")
End If
End Sub
回答by Jkyle Landicho
Yes, Double.Tryparseis the best answer to this question, but to save you time on coding and ensure that the value entered is always numeric, use the NumericDropdown controlinstead of the plain Text Box so that you are sure that inputted value is always numeric and save you time checking the inputted value since that control will not accept anything but numeric values only.
是的,Double.Tryparse是这个问题的最佳答案,但为了节省您的编码时间并确保输入的值始终为数字,请使用NumericDropdown 控件而不是纯文本框,以便您确保输入的值始终为数字并节省您检查输入值的时间,因为该控件只接受数字值。
回答by Ananthan Unni
Use IsNumeric(txtQuantity.Text)
if you have that method defined. Otherwise use Int32.TryParse()
method. It will return true if the text passed in is a number.
IsNumeric(txtQuantity.Text)
如果您定义了该方法,请使用。否则使用Int32.TryParse()
方法。如果传入的文本是数字,它将返回 true。