简体   繁体   中英

Error: Conversion from string “” to type 'Integer' is not valid

Select Case dlg
        Case Windows.Forms.DialogResult.Yes
            If TextBox12.Text = "" Then
                Dim a, b, c As Integer
                a = TextBox7.Text
                b = TextBox8.Text //my problem
                c = TextBox11.Text
                TextBox12.Text = a + b - c
            End If
            If TextBox6.Text = "" Then
                TextBox6.Text = "-"
            End If

I don't know how to fix this error:

Conversion from string "" to type 'Integer' is not valid

Try using Integer.Parse:

Select Case dlg
        Case Windows.Forms.DialogResult.Yes
            If TextBox12.Text = "" Then
                Dim a, b, c As Integer
                a = Integer.Parse(TextBox7.Text)
                b = Integer.Parse(TextBox8.Text) //my problem
                c = Integer.Parse(TextBox11.Text)
                TextBox12.Text = a + b - c
            End If
            If TextBox6.Text = "" Then
                TextBox6.Text = "-"
            End If
If Not String.IsNullOrEmpty(TextBox8.Text) Then           
    b = Integer.Parse(TextBox8.Text)
End If 

You can check if the textbox is empty or null and then use int parse.

Or you could use Pikoh's suggestion of using Int32.TryParse

Int32.TryParse Method

You should look at using Integer.TryParse . The advantage of using TryParse is it won't throw an exception should the conversion fail:

Dim a As Integer = 0
Dim b As Integer = 0
Dim c As Integer = 0

Integer.TryParse(TextBox7.Text, a)
Integer.TryParse(TextBox8.Text, b)
Integer.TryParse(TextBox11.Text, c)

TextBox12.Text = (a + b - c).ToString()

You should also look at setting Option Strict On :

Restricts implicit data type conversions to only widening conversions, disallows late binding, and disallows implicit typing that results in an Object type.

This will help you write better code in the long run.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM