Using Microsoft Visual Basic Express 2010

This is the code i used:

Dim b As Integer = TextBox1.Text
Dim c As Integer = TextBox2.Text
Dim a As Integer = b * c
MsgBox(a

Why does this visual basic code not work and how do i fix it to make it work? It is supposed to multiply any two numbers I input into the text boxes but whenever I 'start debugging', it says:

"Conversion from string "" to type 'Integer' is not valid." and it highlights 'As Integer = TextBox1.Text' (part of first line of text)
Ive been trying to figure out why it wont work for a while now. Please help! And please be detailed in answer.
Thanks

Dani AI

Generated

The problem is that TextBox.Text is a String. The original snippet from attempts to store that string directly in an Integer, so VB tries to convert it and fails when the text is empty or not a pure number — hence the runtime error "Conversion from string "" to type 'Integer' is not valid'." The posted example also shows an incomplete MsgBox call (missing a closing parenthesis), which would be a separate syntax issue.

Several replies point in helpful directions: recommended checking before converting, and suggested explicit conversions, mentioned CInt, and proposed Val. Each approach has tradeoffs — explicit converters throw exceptions on bad input, Val can silently return 0, and IsNumeric is permissive and culture-dependent. A safer, idiomatic pattern in VB.NET is to validate-and-parse together with Integer.TryParse, which returns a Boolean and gives the parsed value without throwing.

Example (use this inside a button-click or other event that runs after input):

Dim leftValue As Integer
If Not Integer.TryParse(TextBox1.Text.Trim(), leftValue) Then
    MessageBox.Show("Enter a valid whole number in the first box.")
    Exit Sub
End If

Dim rightValue As Integer
If Not Integer.TryParse(TextBox2.Text.Trim(), rightValue) Then
    MessageBox.Show("Enter a valid whole number in the second box.")
    Exit Sub
End If

Dim product As Long = CLng(leftValue) * CLng(rightValue)
MessageBox.Show(product.ToString())

Extra tips: enable Option Strict On to catch implicit-conversion mistakes at compile time; use Decimal.TryParse/Double.TryParse for fractional input and pay attention to culture decimal separators; consider a NumericUpDown or masked input to prevent bad characters (an alternative to ’s KeyDown filtering); and choose a larger result type (Long/Decimal) to avoid overflow when multiplying large numbers.

Recommended Answers

All 6 Replies

It looks like it's because TextBox1.Text is of type string. I'm not sure but it may attempt to convert the string into an int where applicable (with inputs such as "20" or "350") and error out otherwise. If the text box is empty, conversion may not be possible. You may need to check if the string can be converted and there's a built in function for this called IsNumeric. You can read more about it below:

http://msdn.microsoft.com/en-us/library/6cd3f6w1%28VS.71%29.aspx

Also, where have you placed the code to work out the value? If this is done as soon as the program loads, it may not work as expected. You will need to do this as part of a button click event handler.

You are trying to assign a string value to an integer variable. In order to do the assignment you should first (as stated by jwdunne) determine that the conversion is possible. If the conversion is possible you can use Convert to do the conversion as in

Dim b As Integer = Convert.ToInt32(textbox1.Text)

Replace "ToInt32" with the appropriate conversion.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim b As Integer = Convert.ToInt32(TextBox1.Text)
    Dim c As Integer = Convert.ToInt32(TextBox2.Text)

    Dim a As Integer = b * c

    MsgBox(a, MsgBoxStyle.OkOnly, )


End Sub

Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown

    Select Case e.KeyCode
        Case Keys.D0, Keys.D1, Keys.D2, Keys.D3, Keys.D4, Keys.D5, Keys.D6, Keys.D7, Keys.D8, Keys.D9
            e.SuppressKeyPress = False

        Case Keys.Subtract, Keys.OemMinus
            If Me.TextBox1.Text.StartsWith("-") Then e.SuppressKeyPress = True
        Case Keys.Delete, Keys.Back, Keys.Enter, Keys.Return
            e.SuppressKeyPress = False
        Case Else
            e.SuppressKeyPress = True
    End Select
End Sub

The keyDown sub will need to be for both text boxes, and you will not be allowed to type in text just +/- intergers

 Dim b As Integer = CInt(TextBox2.Text)
 Dim c As Integer = CInt(TextBox3.Text)
 Dim a As Integer = b * c
 MsgBox(a)

Or, you can shorten the whole thing to one line:

MsgBox(Val(TextBox1.Text) + Val(TextBox2.Text))
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.