2017-05-26 212 views
0

下面顯示的代碼應該允許頁面上的任何按鈕改變顏色,除了在第一個if聲明中指定的那個。此代碼正在工作,但現在單擊按鈕時什麼也不做。該按鈕應該變成黃色,但只是保持默認顏色。無論如何,我可以操縱代碼,所以只有一個按鈕可以一次變紅,而不是允許多個紅色按鈕。在閱讀到這一點。我無法找到任何幫助vb。誰能幫忙?多個按鈕,一個事件來改變點擊按鈕的顏色

個人而言,我認爲這可能與Public Sub有關,因爲消息框在字段爲空時不會顯示。

Public Sub btn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Click 
    Try 
     Dim btn As Button = sender 
     If btn.Name = "BtnUpdate" Or btn.Name = "BtnBackCust" Or btn.Name = "BtnConfirm" Then 
     ElseIf TxtFirstName.Text = "" Or TxtLastName.Text = "" Or TxtAddress.Text = "" Or cboCountry.SelectedItem = "" Or cboRoomType.SelectedItem = "" Then 
      MsgBox("You must populate all fields") 
     Else 
      btn.BackColor = Color.Red 
      btn.Text = ChosenRoom 
     End If 
    Catch ex As Exception 
    End Try 
End Sub 
+1

也許如果你讓代碼拋出異常而不是隱藏它,你可能會發現你的問題。您是否嘗試設置斷點以查看點擊時發生了什麼?你確定它甚至會參加這個活動嗎? –

+0

對於您的其他問題,您可以將當前紅色的按鈕的名稱保存在某個變量中。 –

回答

2

除了使用MyBase.Click事件的,對你的窗體加載爲每個按鈕創建一個手柄:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 
    For Each Button As Button In Me.Controls.OfType(Of Button)() 
     If Button.Name <> "BtnUpdate" AndAlso Button.Name <> "BtnBackCust" AndAlso Button.Name <> "BtnConfirm" Then 
      AddHandler Button.Click, AddressOf ChangeColor 
     End If 
    Next 
End Sub 

ChangeColor分,也創造RedButton變量來跟蹤哪些是當前紅按鈕:

Private RedButton As Button = Nothing 
Private Sub ChangeColor(Sender As Object, e As EventArgs) 
    If TypeOf Sender Is Button Then 
     If TxtFirstName.Text = "" OrElse TxtLastName.Text = "" OrElse TxtAddress.Text = "" OrElse cboCountry.SelectedItem = "" OrElse cboRoomType.SelectedItem = "" Then 
      MsgBox("You must populate all fields") 
     Else 
      Dim SenderButton As Button = Sender 
      If RedButton IsNot Nothing Then 
       RedButton.BackColor = Me.BackColor 
      End If 
      If SenderButton IsNot RedButton Then 'This if will toogle the button between Red and the Normal color 
       SenderButton.BackColor = Color.Red 
      End If 

      RedButton = Sender 
     End If 
    End If 
End Sub 
+0

謝謝。這工作完美 – Matthew