2012-02-25 102 views
0

我正在學習visual basic online,但是我們只是得到了一個老師開關,他們沒有回答我的問題。所以我想我不妨在這裏問一下。我們被要求製作一個僅使用文本框,標籤和按鈕的計算機故障排除程序。我寫了這段代碼,但是當我運行它時,我得到這個錯誤「從字符串」Y「轉換爲鍵入'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 

回答

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 
+0

感謝那些做了。如果他們實施這種改變會更好,因爲這會節省時間,他們都在檢查同樣的事情。 – Photoshopper 2012-02-25 07:10:01

0

If strBeep And strHDD = "Y" Then 

應該

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

And是一個布爾運算符和比較strHDD = "Y"導致了真或假之後它的評估。換句話說,你所寫的並不意味着「如果兩者都是Y」,這意味着如果strBeep爲真,並且strHDD爲「Y」,那麼編譯器沒有意義,因爲strBeep不是真值或假值。

1

更簡潔的方法是儘早從文本框中轉換字符串。因此,不應昏暗strBeep作爲字符串,有:

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 
相關問題