Make checkbox.Checked = True,单击相应的PictureBox

时间:2019-05-22 15:38:15

标签: vb.net

我在Windows窗体中有28个CheckBox。每个框上方都有PictureBox。当用户单击PictureBox时,我想将PictureBox的BackColor更改为绿色,并使其对应的CheckBox.Checked = True

我正在使用的代码:

Private Sub PictureBox1_Click
    PictureBox1.BackColor = Color. Green 
    CheckBox1.Checked = true 

对于28,这将是一个漫长的过程。有什么简单的解决方法吗?

2 个答案:

答案 0 :(得分:1)

以编程方式将MouseClick甚至处理程序添加到Form_Load中的所有PictureBox中。事件处理程序将解析发送方(PictureBox),并根据相应控件的名称以相同索引结尾的事实找到CheckBox。表单关闭时删除处理程序。

Private pictureBoxPrefix As String = "PictureBox"
Private checkBoxPrefix As String = "CheckBox"

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    For Each pb In Me.Controls.OfType(Of PictureBox).Where(Function(p) p.Name.Contains(pictureBoxPrefix))
        AddHandler pb.MouseClick, AddressOf PictureBox_MouseClick
    Next
End Sub

Private Sub PictureBox_MouseClick(sender As Object, e As MouseEventArgs)
    Dim index = Integer.Parse(pb.Name.Replace(pictureBoxPrefix, ""))
    Dim pb = CType(sender, PictureBox)
    Dim cb = CType(Me.Controls.Find($"{checkBoxPrefix}{index}", True).First(), CheckBox)
    pb.BackColor = Color.Green
    cb.Checked = True
End Sub

Private Sub Form1_Closed(sender As Object, e As EventArgs) Handles Me.Closed
    For Each pb In Me.Controls.OfType(Of PictureBox).Where(Function(p) p.Name.Contains(pictureBoxPrefix))
        RemoveHandler pb.MouseClick, AddressOf PictureBox_MouseClick
    Next
End Sub

答案 1 :(得分:0)

在窗体的Load()事件中,使用Controls.Find()获取对PictureBoxes和CheckBoxes的引用。将CheckBox引用存储在每个PictureBox的Tag()属性中。连接您的PB的Click()事件。在这种情况下,请更改PB的颜色,然后从Tag()属性中检索CheckBox并同时选中该框:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    For i As Integer = 1 To 28
        Dim PB As PictureBox = Me.Controls.Find("PictureBox" & i, True).FirstOrDefault
        Dim CB As CheckBox = Me.Controls.Find("CheckBox" & i, True).FirstOrDefault
        If Not IsNothing(PB) AndAlso Not IsNothing(CB) Then
            PB.Tag = CB
            CB.Tag = PB
            AddHandler PB.Click, AddressOf PB_Click
            AddHandler CB.CheckedChanged, AddressOf CB_CheckedChanged
        End If
    Next
End Sub

Private Sub PB_Click(sender As Object, e As EventArgs)
    Dim pb As PictureBox = DirectCast(sender, PictureBox)
    Dim cb As CheckBox = DirectCast(pb.Tag, CheckBox)
    If pb.BackColor.Equals(Color.Green) Then
        pb.BackColor = Color.Empty
        cb.Checked = False
    Else
        pb.BackColor = Color.Green
        cb.Checked = True
    End If
End Sub

Private Sub CB_CheckedChanged(sender As Object, e As EventArgs)
    Dim cb As CheckBox = DirectCast(sender, CheckBox)
    Dim pb As PictureBox = DirectCast(cb.Tag, PictureBox)
    pb.BackColor = If(cb.Checked, Color.Green, Color.Empty)
End Sub