How do I convert from a string to an integer in Visual Basic?

后端 未结 7 1054
死守一世寂寞
死守一世寂寞 2020-12-15 15:06

How do I convert from a string to an integer? Here\'s what I tried:

Price = CInt(Int(txtPrice.Text))

I took out the Int and I

相关标签:
7条回答
  • 2020-12-15 15:28

    Use

    Convert.toInt32(txtPrice.Text)
    

    This is assuming VB.NET.

    Judging by the name "txtPrice", you really don't want an Integer but a Decimal. So instead use:

    Convert.toDecimal(txtPrice.Text)
    

    If this is the case, be sure whatever you assign this to is Decimal not an Integer.

    0 讨论(0)
  • 2020-12-15 15:29

    You can try these:

    Dim valueStr as String = "10"
    
    Dim valueIntConverted as Integer = CInt(valueStr)
    

    Another example:

    Dim newValueConverted as Integer = Val("100")
    
    0 讨论(0)
  • 2020-12-15 15:29

    Use Val(txtPrice.text)

    I would also allow only number and the dot char by inserting some validation code in the key press event of the price text box.

    0 讨论(0)
  • 2020-12-15 15:33

    You can try it:

    Dim Price As Integer 
    Int32.TryParse(txtPrice.Text, Price) 
    
    0 讨论(0)
  • 2020-12-15 15:34

    Please try this, VB.NET 2010:

    1. Integer.TryParse(txtPrice.Text, decPrice)
    2. decPrice = Convert.ToInt32(txtPrice.Text)

    From Mola Tshepo Kingsley (WWW.TUT.AC.ZA)

    0 讨论(0)
  • 2020-12-15 15:35

    Convert.ToIntXX doesn't like being passed strings of decimals.

    To be safe use

    Convert.ToInt32(Convert.ToDecimal(txtPrice.Text))
    
    0 讨论(0)
提交回复
热议问题