多个按钮,一个事件来改变点击按钮的颜色

问题描述:

下面显示的代码应该允许页面上的任何按钮改变颜色,除了在第一个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

对于您的其他问题,您可以将当前红色的按钮的名称保存在某个变量中。 –

除了使用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