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

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 still got an exception.



Solution 1:[1]

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.

Solution 2:[2]

You can try it:

Dim Price As Integer 
Int32.TryParse(txtPrice.Text, Price) 

Solution 3:[3]

You can use the following to convert string to int:

  • CInt(String) for ints
  • CDec(String) for decimals

For details refer to Type Conversion Functions (Visual Basic).

Solution 4:[4]

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)

Solution 5:[5]

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

To be safe use

Convert.ToInt32(Convert.ToDecimal(txtPrice.Text))

Solution 6:[6]

You can try these:

Dim valueStr as String = "10"

Dim valueIntConverted as Integer = CInt(valueStr)

Another example:

Dim newValueConverted as Integer = Val("100")

Solution 7:[7]

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.

Solution 8:[8]

If there might be invalid characters in the textbox it will throw an exception. The Val command pulls numbers and strips invalid characters. It returns a double. So you want to convert the result of Val to whatever type you need.

Price = Convert.toInt32(Val(txtPrice.Text))

This will return 0 instead of throwing an error on invalid input. If that isn't desired you should be checking that the input is valid before you convert.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Mortensen
Solution 2 zari
Solution 3 Peter Mortensen
Solution 4 Bugs
Solution 5 stuartdotnet
Solution 6 Peter Mortensen
Solution 7 Nandostyle
Solution 8 HackSlash