从类型 string 到 double 的转换无效

Conversion from type string to double is not valid

我有一些非常简单的 vb.net 代码并收到此错误消息。我想要做的是检查 btn3 是否被按下以及 tbAantalIslands 是否高于或低于 2 并相应地更改按钮的颜色。

我在互联网上搜索了一下,确实找到了解决方法,如果我给 tbAantalIslands 一个值,它就可以工作。但是我的程序要求用户自己填写值,但是如果我留空就会出现这个错误。

这是我的代码:

        'it works when i give tbAantalIslands.Text a value, but thats not what I want to do

        ' tbAantalIslands.Text = 1

        If tbAantalIslands.Text > 2 Then

            If iBtnClickCheck > 0 Then
                btn3.BackColor = Color.Red

            End If

        ElseIf tbAantalIslands.Text < 2 Then
            If iBtnClickCheck > 0 Then
                btn3.BackColor = Color.Green

            End If

        End If

试试这个:

        If IsNumeric(tbAantalIslands.Text) AndAlso Integer.Parse(tbAantalIslands.Text) > 2 Then
            If iBtnClickCheck > 0 Then btn3.BackColor = Color.Red
        ElseIf IsNumeric(tbAantalIslands.Text) AndAlso Integer.Parse(tbAantalIslands.Text) < 2 Then
            If iBtnClickCheck > 0 Then btn3.BackColor = Color.Green
        End If

验证和转换的正确方法是使用适当的 TryParse 方法:

Dim aantalIslands As Integer

If Integer.TryParse(tbAantalIslands.Text, aantalIslands) Then
    If aantalIslands > 2 Then
        '...
    ElseIf aantalIslands < 2 Then
        '...
    End If
End If

编辑:

根据最近的评论,您似乎应该像这样调整 If 语句:

Dim aantalIslands As Integer

If Integer.TryParse(tbAantalIslands.Text, aantalIslands) Then
    If aantalIslands > 2 Then
        '...
    Else
        '...
    End If
End If

实际上,鉴于您正在做的事情,如果让整个事情更简洁会更好:

Dim aantalIslands As Integer

If Integer.TryParse(tbAantalIslands.Text, aantalIslands) AndAlso
   iBtnClickCheck > 0 Then
    btn3.BackColor = If(aantalIslands > 2, Color.Red, Color.Green)
End If

您关闭了 Option Strict,并且编译器在 tbAantalIslands.Text > 2 上添加了从字符串到双精度的隐式转换。隐式转换不进行任何验证或错误检查,并且当值不是双精度值时它会失败。

我建议打开 Option Strict On,以发现此类问题,并使用输入验证进行显式转换。