将Textbox值转换为Integer

时间:2015-09-16 09:16:38

标签: vb.net casting textbox integer

我有以下整数变量

Dim sMaxAmount As Integer
Dim sMinAmount As Integer

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

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

虽然我将其转换为Integer但我得到了异常

  

无法转换类型为#System; Web.UI.WebControls.TextBox&#39;的对象。至   键入&#39; System.IConvertible&#39;。

我做错了什么?

3 个答案:

答案 0 :(得分:1)

错字:使用txtTransactionAmount.Text代替txtTransactionAmount

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

答案 1 :(得分:0)

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

  1. 您没有验证TextBox的内容。如果用户输入了无法转换为整数的内容,则会抛出异常。
  2. 考虑到变量的名称,您正在进行的测试没有意义。 TextBox中的值不能 小于最小值且大于最大值。
  3. 以下代码使用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
    

答案 2 :(得分:0)

Val(TextBox.Text)会将TextBox的值转换为Integer。

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