InvalidCastException指定的强制转换无效

时间:2014-11-01 20:14:22

标签: vb.net if-statement label picturebox

如果TextBox1和TextBox2文本等于明确的单词,我不想制作PictureBox和Label。

但我收到错误......
请帮忙

以下是代码:

Public Class Appearance
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If TextBox1.Text = "Brown" & TextBox2.Text = "Brown" Then
            PictureBox4.Image = My.Resources.brown
            PictureBox2.Image = My.Resources.blue
            PictureBox5.Image = My.Resources.green
            PictureBox4.Visible = True
            PictureBox2.Visible = True
            PictureBox5.Visible = True
            Label7.Visible = True
            Label8.Visible = True
            Label9.Visible = True
        End If
    End Sub
End Class

2 个答案:

答案 0 :(得分:1)

在VB.NET中,&表示string concatenation。您可能想要使用AndAlso

If TextBox1.Text = "Brown" AndAlso TextBox2.Text = "Brown" Then

答案 1 :(得分:0)

  

编辑:对不起,想念您想将TextBox1和TextBox2值都比较为一个字符串值

Neolisk已经提供了正确的评估:

    If TextBox1.Text = "Brown" AndAlso TextBox2.Text = "Brown" Then

  

编辑:以下建议是错误的。

替换此

    If TextBox1.Text = "Brown" & TextBox2.Text = "Brown" Then

由此:

    If TextBox1.Text = TextBox2.Text Then

  

编辑:我在这里留下解释

如果你写If TextBox1.Text = "Brown" & TextBox2.Text = "Brown" Then,我们认为TextBox2.Text “Brown”正在发生的事情是:

  • 由于&用于VB中的字符串连接,就像+一样,TextBox1.Text将与链"Brown" & TextBox2.Text = "Brown"进行比较。
  • 使用"Brown" & TextBox2.Text = "Brown",将首先评估"Brown" & TextBox2.Text,因为&字符串连接符优先于=布尔值评估。你会得到连接的字符串"BrownBrown"(=“布朗”)。
  • 但是,您将拥有"BrownBrown" = "Brown",在此阶段,完整的评估链为If TextBox1.Text = "BrownBrown" = "Brown" Then
  • TextBox1.Text = "BrownBrown"将首先评估,并返回False。最后,您正在评估:

    If False = "Brown" Then ' <- Boolean comparison with String Error !

由于您是VB的新手,很高兴知道:

请注意AndAlso具有快捷功能。如果左侧部分的评估为False,则右侧部分不会评估。

要评估左右两侧,有And比较器。但是,老实说,比较

    If False = True And "SameValue" = "SameValue" ' will always return False.

如果左侧已经False,则在比较右侧没有意义。您应该知道这是VB的唯一故障。 但是,我不知道它是否已修复,因为 。但如果不是,则同样适用于OrOrElse

=&GT;您最好从头开始使用AndAlsoOrElse代替And/Or