【问题标题】:Error: Conversion from string "" to type 'Integer' is not valid错误:从字符串“”到类型“整数”的转换无效
【发布时间】:2017-01-23 09:47:16
【问题描述】:
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

我不知道如何解决这个错误:

从字符串“”到类型“整数”的转换无效

【问题讨论】:

  • 您不能将空字符串转换为 Int。在尝试分配给 int 变量之前,您应该检查文本框是否为空
  • 开启Option Strict On。从长远来看,这将有所帮助。你需要Integer.TryParse(TextBox7.Text, a)
  • Khakim,你应该考虑接受这个问题的答案之一。对您有帮助的答案将是显而易见的选择。它可以帮助该帖子的未来读者,还可以帮助您获得一点代表。

标签: vb.net visual-studio


【解决方案1】:

尝试使用 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

【讨论】:

  • 我建议改用Int32.TryParse,因为我认为(我不习惯vb.net)如果字符串为空,这也会引发异常
【解决方案2】:
If Not String.IsNullOrEmpty(TextBox8.Text) Then           
    b = Integer.Parse(TextBox8.Text)
End If 

您可以检查文本框是否为空或为空,然后使用 int 解析。

或者你可以使用 Pikoh 的建议使用Int32.TryParse

Int32.TryParse Method

【讨论】:

  • 不应该是If Not String.IsNullOrEmpty(..
【解决方案3】:

你应该看看使用Integer.TryParse。使用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()

你还应该看看设置Option Strict On

将隐式数据类型转换限制为仅扩展转换,禁止后期绑定,并禁止导致 Object 类型的隐式类型。

从长远来看,这将帮助您编写更好的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多