vb.net 错误:从字符串 "" 到类型 'Integer' 的转换无效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41803276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error: Conversion from string "" to type 'Integer' is not valid
提问by khakim
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' 的转换无效
回答by Svekke
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
回答by Cal-cium
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
回答by Bugs
You should look at using Integer.TryParse. The advantage of using TryParseis it won't throw an exception should the conversion fail:
您应该考虑使用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()
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.
将隐式数据类型转换限制为仅扩展转换,禁止后期绑定,并禁止导致 Object 类型的隐式类型化。
This will help you write better code in the long run.
从长远来看,这将帮助您编写更好的代码。

