vb.net 将文本框值转换为整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32604382/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 19:28:12  来源:igfitidea点击:

Convert Textbox value to Integer

vb.netcastingtextboxinteger

提问by Nuke

I have the following Integer variables

我有以下整数变量

Dim sMaxAmount As Integer
Dim sMinAmount As Integer

I am trying to compare them with a TextBox field.

我正在尝试将它们与 TextBox 字段进行比较。

If (Convert.ToInt32(txtTransactionAmount) < sMinAmount And Convert.ToInt32(txtTransactionAmount) > sMaxAmount) Then

Although I am converting it to IntegerI get exception

虽然我正在将其转换为Integer我得到异常

Unable to cast object of type 'System.Web.UI.WebControls.TextBox' to type 'System.IConvertible'.

无法将“System.Web.UI.WebControls.TextBox”类型的对象转换为“System.IConvertible”类型。

What am I doing wrong?

我究竟做错了什么?

回答by Reagan Gallant

Typo: use txtTransactionAmount.Textinstead of txtTransactionAmount

错别字:使用txtTransactionAmount.Text代替txtTransactionAmount

If (Convert.ToInt32(txtTransactionAmount.Text) < sMinAmount AndAlso Convert.ToInt32(txtTransactionAmount.Text) > sMaxAmount) 

回答by Blackwood

In addition to not using the Text property to get the string contained in the TextBox, there are two other problems with your code.

除了不使用 Text 属性来获取包含在 TextBox 中的字符串之外,您的代码还有另外两个问题。

  1. You are not validating the contents of the TextBox. If the user enters something that can't be converted to an integer, an exception will be thrown.
  2. The test you are doing doesn't make sense given the names of the variables. The value in the TextBox can't be bothless than the minimum and more than the maximum.
  1. 您没有验证 TextBox 的内容。如果用户输入的内容无法转换为整数,则会抛出异常。
  2. 鉴于变量的名称,您正在进行的测试没有意义。TextBox 中的值不能小于最小值又大于最大值。

The following code uses Integer.TryParseto validate the contents of the TextBox and convert it to an Integer. It also checks that the value in greater than or equal to sMinAmountand less than or equal to sMaxAmount.

以下代码使用Integer.TryParse验证 TextBox 的内容并将其转换为 Integer。它还检查 中的值是否大于或等于sMinAmount且小于或等于sMaxAmount

Dim amount As Integer
If Integer.TryParse(txtTransactionAmount.Text, amount) _
  AndAlso amount >= sMinAmount AndAlso aamount <= sMaxAmount Then
    'The Integer called "amount" now contains a value between sMinAmount and sMinAmount
End If

回答by Nover Yearfourth

Val(TextBox.Text)will convert the value of a TextBox to an Integer.

Val(TextBox.Text)将文本框的值转换为整数。

txtTotal.text= Val(txtPrice.text) * Val(txtQuantity.text)```