将String转换为integer并将null等于0

时间:2017-01-27 08:54:14

标签: vb.net type-conversion

我知道有没有简单的方法来执行此操作?当a.text为null时,它会出错。如果我没有逐个检测到,使用简单的代码我可以将a.text null转换为0吗?

Dim count1 As Integer = 0
count1 = Convert.ToInt32(a.Text) + Convert.ToInt32(b.Text) + Convert.ToInt32(c.Text)
txt_display.Text = count1

有任何其他方法,而不是我喜欢下面逐一检测。

if a.Text = "" Then
a.Text = 0
End If

5 个答案:

答案 0 :(得分:3)

如果您的目标是对文本框中的值求和并忽略无法转换为整数的文本框,那么您只需使用Int32.TryParse
如果在不抛出异常的情况下无法将文本转换为整数,它会将变量设置为0。

' In place of your textboxes
Dim x1 As String = "2"
Dim x2 As String = Nothing
Dim x3 As String = "5"

Dim a, b, c As Integer

Int32.TryParse(x1, a)
Int32.TryParse(x2, b)
Int32.TryParse(x3, c)

Dim result = a + b + c
Console.WriteLine(result)

相反,如果你想在文本框文本中写入“0”字符串来向用户发出错误输入的信号,那么你必须逐个检查文本框,再次使用Int32.TryParse

Dim value1 as Integer
if Not Int32.TryParse(a.Text, value1) Then
   a.Text = "0"
End If

' Here the variable value1 contains the converted value or zero.
' repeat for the other textboxes involved

答案 1 :(得分:3)

你必须逐个检测。更好的方法,就是创建自己的功能。请尝试以下。

Dim count1 As Integer = 0
count1 = ConvertToInteger(a.Text) + ConvertToInteger(b.Text) + ConvertToInteger(c.Text)
txt_display.Text = count1




Private Function ConvertToInteger(ByRef value As String) As Integer
    If String.IsNullOrEmpty(value) Then
        value = "0"
    End If
    Return Convert.ToInt32(value)
End Function

答案 2 :(得分:1)

示例:

If String.IsNullOrEmpty(a.Text) Then
 a.Text = "0"
End If

答案 3 :(得分:1)

使用If运算符的另一种方法:

Dim count1 As Integer = 0
count1 = If(String.IsNullOrEmpty(a.Text), 0, Convert.ToInt32(a.Text)) + If(String.IsNullOrEmpty(b.Text), 0, Convert.ToInt32(b.Text)) + If(String.IsNullOrEmpty(c.Text), 0, Convert.ToInt32(c.Text))
txt_display.Text = count1

答案 4 :(得分:0)

根据Microsoft Documentation,空字符串(Nothing)与空字符串("")不同:

  

String的默认值为Nothing(空引用)。请注意,这与空字符串(值“”)不同。

您还可以使用=运算符,在使用String类型时可能会比较棘手。有关更多信息,请参见this post和获得50分悬赏的答案。

如果您使用If with only two arguments,则以下代码

If a.Text Is Nothing Then
    a.Text = 0
End If

可以变成单线:Dim MyNumber as Integer = If(a.Text, 0)

如果您打算使用空字符串,则可以使用:Dim MyNumber as Integer = If(a.Text.Length = 0, 0, a.Text)

如果您要同时处理这两个问题,可以按照当前接受的答案的建议使用String.IsNullOrEmpty(a.Text);或者您可以使用a.Text=""a.Text = String.Emptya.Text = vbNullString,它们都是相等的(请参见post I referred to earlier

最后,请注意,从String类型到Integer类型的转换是隐式进行的。不需要使用显式强制转换,例如CType()Convert.ToInt32

相关问题