简体   繁体   English

错误:从字符串“”到类型“ Integer”的转换无效

[英]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 从字符串“”到类型“ Integer”的转换无效

Try using Integer.Parse: 尝试使用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. 您可以检查文本框是否为空或为空,然后使用int解析。

Or you could use Pikoh's suggestion of using Int32.TryParse 或者你可以使用使用Pikoh的建议Int32.TryParse

Int32.TryParse Method Int32.TryParse方法

You should look at using Integer.TryParse . 您应该看看使用Integer.TryParse The advantage of using TryParse is it won't throw an exception should the conversion fail: 使用TryParse的优点是,如果转换失败,它将不会引发异常:

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 : 您还应该查看将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. 从长远来看,这将帮助您编写更好的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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