string to integer conversion

skaryChinezeGuie

Well-known member
Joined
Apr 23, 2006
Messages
94
Programming Experience
Beginner
the problem is that option strict won't allow string to integer conversion. How can i work around this or fix it? thanks in advance.:D

VB.NET:
[SIZE=2][COLOR=#0000ff]Private[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Sub[/COLOR][/SIZE][SIZE=2] BtnDeposit_Click([/SIZE][SIZE=2][COLOR=#0000ff]ByVal[/COLOR][/SIZE][SIZE=2] sender [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] System.Object, [/SIZE][SIZE=2][COLOR=#0000ff]ByVal[/COLOR][/SIZE][SIZE=2] e [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE]
 
[SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] myMoney [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Integer[/COLOR][/SIZE][SIZE=2] = Money
[/SIZE][SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] myBank [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Integer[/COLOR][/SIZE][SIZE=2] = Bank
[/SIZE][SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] DepositAmount [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Integer[/COLOR][/SIZE][SIZE=2] = [B][I][U][COLOR=red]TxtDeposit.Text[/COLOR][/U][/I][/B]
[/SIZE]
[SIZE=2][COLOR=#0000ff]If[/COLOR][/SIZE][SIZE=2] DepositAmount <= myMoney [/SIZE][SIZE=2][COLOR=#0000ff]Then
[/COLOR][/SIZE][SIZE=2]Bank = myBank + DepositAmount
Money = myMoney - DepositAmount
[/SIZE][SIZE=2][COLOR=#0000ff]Call[/COLOR][/SIZE][SIZE=2] FrmBank_Load([/SIZE][SIZE=2][COLOR=#0000ff]Me[/COLOR][/SIZE][SIZE=2], [/SIZE][SIZE=2][COLOR=#0000ff]New[/COLOR][/SIZE][SIZE=2] System.EventArgs)
[/SIZE][SIZE=2][COLOR=#0000ff]Else
[/COLOR][/SIZE][SIZE=2]MessageBox.Show("Try Again")
[/SIZE][SIZE=2][COLOR=#0000ff]End[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]If
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]End[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Sub
[/COLOR][/SIZE]
[SIZE=2][COLOR=#0000ff]Private[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Sub[/COLOR][/SIZE][SIZE=2] BtnWithdraw_Click([/SIZE][SIZE=2][COLOR=#0000ff]ByVal[/COLOR][/SIZE][SIZE=2] sender [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] System.Object, [/SIZE][SIZE=2][COLOR=#0000ff]ByVal[/COLOR][/SIZE][SIZE=2] e [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE]
 
[SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] myMoney2 [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Integer[/COLOR][/SIZE][SIZE=2] = Money
[/SIZE][SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] myBank2 [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Integer[/COLOR][/SIZE][SIZE=2] = Bank
[/SIZE][SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] WithdrawAmount [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Integer[/COLOR][/SIZE][SIZE=2] = [B][I][U][COLOR=red]TxtWithdraw.Text[/COLOR][/U][/I][/B]
[/SIZE]
[SIZE=2][COLOR=#0000ff]If[/COLOR][/SIZE][SIZE=2] WithdrawAmount <= myBank2 [/SIZE][SIZE=2][COLOR=#0000ff]Then
[/COLOR][/SIZE][SIZE=2]Bank = myBank2 - WithdrawAmount
Money = myMoney2 + WithdrawAmount
[/SIZE][SIZE=2][COLOR=#0000ff]Call[/COLOR][/SIZE][SIZE=2] FrmBank_Load([/SIZE][SIZE=2][COLOR=#0000ff]Me[/COLOR][/SIZE][SIZE=2], [/SIZE][SIZE=2][COLOR=#0000ff]New[/COLOR][/SIZE][SIZE=2] System.EventArgs)
[/SIZE][SIZE=2][COLOR=#0000ff]Else
[/COLOR][/SIZE][SIZE=2]MessageBox.Show("Try Again")
[/SIZE][SIZE=2][COLOR=#0000ff]End[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]If
[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]End[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Sub
[/COLOR][/SIZE]
 
Last edited by a moderator:
Use the CInt function. Why would you want to code with the Option Strict = On ?
 
JohnH said:
Use the CInt function. Why would you want to code with the Option Strict = On ?
Zoiks! Everyone should always have Option Strict turned On. In my opinion it is a travesty that the default is Off. It should be On by default and then when you understand the implications you can turn it Off in those very few situations where it is appropriate. The way VB works with Option Strict Off is one of the main reasons that users of other languages look down on VB and its users. Having Option Strict On forces you to use early binding and make all your conversions explicit. That means that your code will run more efficiently and be less likely to crash, plus it makes you a better developer by making you understand where and why conversions are taking place. I'm astounded by the number of people who don't even realise that a conversion is taking place when you assign the Text from a TextBox to a numeric variable.

As for your question, you should NOT be using CInt, CType or any of those unless you can be 100% sure that the user is going to enter valid data. If you have not added some sort of validation to that TextBox then what's to stop the user entering anything they like? If you use CInt, CType or anything else absolute like that your app will crash. In the absence of any other validation you should be using TryParse, e.g.
VB.NET:
Dim depositAmount As Integer

If Not Integer.TryParse(txtDeposit.Text, depositAmount) Then
    MessageBox.Show("You have entered an invalid deposit amount.")
    Return
End If
If the TextBox contains a valid Integer then TryParse returns True and the parsed value is contained in the depositAmount variable. If the TextBox contains anything that cannot be converted to an Integer then TryParse returns False, without throwing an exception. This makes your app more robust and more efficient.
 
Ah, I thought I noticed that you were using 2005 but after vis781's post I looked again and and now I see you're using 2003. Double.TryParse was the only option in 2003 so it's a little more complex but only a little:
VB.NET:
Dim depositAmount As Integer
Dim dummy As Double

If Double.TryParse(txtDeposit.Text, _
                   Globalization.NumberStyles.Integer, _
                   Nothing, _
                   dummy) Then
    'We now know that 'dummy' contains a valid integer.
    depositAmount = CInt(dummy)
Else
    MessageBox.Show("You have entered an invalid deposit amount.")
    Return
End If
 
Here's a bit of backup for Kulrom's argument. Personally, I only ever use CInt, CStr, etc. for casting, i.e. when the object is already of that type and I just want a reference of the same type, e.g.
VB.NET:
Dim al As New ArrayList

al.Add("Hello World")

Dim str As String = CStr(al(0))
The underlying object is already a String, but you need to cast the Object reference as type String to use it, at least if you have Option Strict On anyway. ;)

Note that those time differences are despite CInt and CStr being compiled inline, i.e. the compiled code does not make a function call so does not create a stack frame.
 

Attachments

  • CastOperators.JPG
    CastOperators.JPG
    127.9 KB · Views: 70
I only did copy/paste of the post i left the link for .. well not entire post is related to this subject but there is a part which IS ... ;)


Visual Basic .NET/2005 has many ways to convert values. Some of them are updated versions of VB6 techniques while some was added in the new version(s).
However, many programmer are using these short conversion method which most VB6 programmers are familiar with. These methods for conversion of primitive datatypes are boxing the value type which has performance implication.
For example, CStr class will convert primitive type to a String but it has an advantage. It is that CStr is designed to support any object which means that if primitive type is used the method CStr automatically boxes the parameter prior to getting the new value.
This result in a loss of performance.
The conversions run faster when the members of the Convert class are called explicitly (Convert.ToInt32(value)).
Finally, althrough Cint(0,5) will compile it will not always execute correctly just like in you case. Means it is not about what you like but rather what is best for your application.
Regards ;)
 
JohnH said:
Use the CInt function. Why would you want to code with the Option Strict = On ?

Option Strict rules! It makes things a lot more long winded and yada yada, like other languages that have a more-like-c syntax :D

Makes me feel very much at home :)


On a serious note, it can improve the performance of the app if you state at design time the types of objects youre dealing with. This helps avoid late biding resolution at runtime, amongst other things that Microsoft say slows down your app :)
 
vis781 said:
You may also want to look into...

VB.NET:
Double.TryParse

On a related note, in vb, i've always used the java-esque (number type).Parse or (number type).ParseExact.. tryparse is perhaps marginally more useful because youre told whether it failed or not, which saves you catching and dealing with a whole load of exceptions.
 
Of course I see benefits with Option Strict (On) at some level, but (Off) it is also one of the better entry level supports and probably the most unique feature of the Visual Basic language through times. Along with a few other features is it what makes Visual Basic so easy to start learning, what made it so popular and also reckoned productive environment. So I was partly curious as to why skaryChinezeGuie would want to 'go there' yet. Also for what we know skaryChinezeGuie could already be doing proper validation of that Textbox already (well I don't really think so.. hehheh :)), then when handling the click processing a pure c-whatever conversion would do.
 
john is not funny. I "went there" for one because it was recommended to me, and two because after turning it on i actually realized the logic mistakes i made. My program was working perfectly until i turned it on. But now that it's on i think it will stay on because it guides proper logic, makes me come here to get made fun of, and the only thing good ********* is the Death Metal. Dunt! Du Da duh Dunt!

so... double.tryparse? riiiiighht. is that a newbie trick that makes my computer explode? bad joke.
 
Last edited by a moderator:
skaryChinezeGuie said:
john is not funny. I "went there" for one because it was recommended to me, and two because after turning it on i actually realized the logic mistakes i made. My program was working perfectly until i turned it on. But now that it's on i think it will stay on because it guides proper logic, makes me come here to get made fun of, and the only thing good in Norway is the Death Metal. Dunt! Du Da duh Dunt!

Your program can work perfetly again, if you correct all the errors by instructing vb to do explicitly (directly) what it was doing implicitly (vb was guessing)

On an unrelated note- Im sure you apreciate this forum is read by many people who speak the language of english, but have different cultural and personal perspectives on the world. As a reasonably empathic, native english speaker I wanted to tell you I found this post quite 'hard' or 'aggressive' towards John. I'm sure youre making a joke, but its quite hard to tell what tone you wished to assign to the words. John isnt likely to be upset because he's very laid back and quite emotionally disconnected with regards to what people say to him on the internet, but there are other members on here who, had your post been addressed to them, would have parsed it as quite a probing attack on the advice they gave or their nationality and might well have responded quite strongly. Perhaps you could consider using more smilies to convey the impression of how youre saying these words?

so... double.tryparse? riiiiighht. is that a newbie trick that makes my computer explode? bad joke.
tryparse is a very useful function - it handles all conversion problems internally and gives 2 results: one of whether the conversion succeeded or not, and the other the value you can use if it did succeed. On your version of the framework it looks a bit wordy and long-winded, but that's why you'd create your own Function to perform the work. Remember to pass your Integer parameter ByRef rather than byval, because it is not mutable and assignment changes will be lost if the pointer isnt passed by reference
 
Back
Top