从字符串“Y”到“布尔”类型的转换无效

时间:2012-02-25 07:02:08

标签: .net string visual-studio visual-studio-2010 boolean

我正在网上学习视觉基础知识,但是我们只是有一个教师转换,他们没有回复我的问题。所以我想我也可以在这里问一下。我们要求制作仅使用文本框,标签和按钮的计算机故障排除程序。我写了这段代码,但是当我运行它时,我收到此错误“从字符串转换”Y“到类型'布尔'无效。”我不知道为什么或如何解决它。谢谢你的帮助。

Private Sub btnHelp_Click(sender As Object, e As System.EventArgs) Handles btnHelp.Click
        Dim strBeep As String
        Dim strHDD As String

        strBeep = Me.txtBeep.Text
        strHDD = Me.txtHDD.Text


        If strBeep And strHDD = "Y" Then
            Me.lblMessage.Text = "Contact tech support."

        ElseIf strBeep = "Y" And strHDD = "N" Then
            Me.lblMessage.Text = "Check drive contacts."

        ElseIf strBeep And strHDD = "N" Then
            Me.lblMessage.Text = "Bring computer to repair center."

        ElseIf strBeep = "N" And strHDD = "Y" Then
            Me.lblMessage.Text = "Check the speaker connections."
        End If
    End Sub
End Class

3 个答案:

答案 0 :(得分:1)

更简洁的方法是尽早从文本框转换字符串。因此,不要让Dim strBeep As String,而是:

Dim bBeep As Boolean
Dim bHDD As Boolean

bBeep = (Me.txtBeep.Text = "Y")
bHDD = (Me.txtHDD.Text = "Y")

然后你的if语句如下所示:

If bBeep And bHDD Then
    'do something
Else If bBeep And Not bHDD
    'do something else
End If

答案 1 :(得分:0)

您在if条件中使用strBeep而未将其与某些内容进行比较。这是一个文本,无法转换为boolean

这样做:

 if strBeep = "Y" ...

而不是

 if strBeep ...

完成条件:

 If strBeep = "Y" And strHDD = "Y" Then
        Me.lblMessage.Text = "Contact tech support."
 ElseIf strBeep = "Y" And strHDD = "N" Then
        Me.lblMessage.Text = "Check drive contacts."
 ElseIf strBeep = "N" And strHDD = "N" Then
        Me.lblMessage.Text = "Bring computer to repair center." 
 ElseIf strBeep = "N" And strHDD = "Y" Then
        Me.lblMessage.Text = "Check the speaker connections."
 End If

答案 2 :(得分:0)

If strBeep And strHDD = "Y" Then

应该是

If strBeep = "Y" And strHDD = "Y" Then

And是一个布尔运算符,它在比较strHDD = "Y"导致true或false后进行评估。换句话说,你所写的并不意味着“如果两者都是Y”,则意味着strBeep为真且strHDD为“Y”,编译器没有意义,因为strBeep不是真值或假值。