string to integer not valid

bdvincent

New member
Joined
Jan 1, 2008
Messages
2
Programming Experience
Beginner
Hey all, extremely EASY question here but I can't figure it out.

I installed Visual Basic 2008 Professional and I'm teaching myself through a beginner's tutorial online. On this exercise I have to pass two textboxes to Integer variables and then add the number's in the textboxes in a Loop. A message box will then pop up with the answer.

However the part I'm STUCK at is when I check if the user has entered anything into the textboxes. If not I will just Exit Sub, but it keeps giving me a
"Conversion from string "" to type 'Integer' is not valid." error.
Here is my code:

VB.NET:
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim startNumber As Integer
        Dim endNumber As Integer
        Dim answer As Integer

        startNumber = TextBox1.Text
        endNumber = TextBox2.Text

        If startNumber = "0" OrElse endNumber = "0" Then
            Exit Sub
        End If

        For i = startNumber To endNumber

            answer = answer + i

        Next i

        MsgBox(answer)

    End Sub
 
The textbox.text value will be a string. Convert it to an integer as follows:

You have to put them in try thingies as they may not contain integer values in the textbox.

try
startnumber = cint(textbox1.text)
endNumber = cint(textbox2.text)
catch ex as exception
end try

Hope that helps.
 
Hi whitespire,

I simply changed this for my code:

startNumber = Val(Textbox1.Text)
endNumber = Val(Textbox2.Text)

and it is no longer giving me errors... could this work correctly??
 
There is also the TryParse method.
VB.NET:
Dim i As Integer
If Integer.TryParse(TextBox1.Text, i) Then
    'i now got number.
Else
    'no possible conversion from string to integer.
End If
You can also use controls that only accept numeric input from user, like NumericUpDown or MaskedTextBox with mask set to numeric.
 
Back
Top