多个按钮,一个事件可以更改单击的按钮颜色

时间:2017-05-26 16:02:17

标签: vb.net button

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