Okay so I have about 100 pictureboxes and I want them to change colour when you click them. I don't want to write the code for every picturebox individually because that would take ages. I've come up with this code but it doesn't work despite having no errors, why?

Public Class frmFriday

    Dim btn As PictureBox

    Private Sub btn_click(ByVal sender As Object, ByVal e As System.EventArgs)
        btn.BackColor = Color.Blue
    End Sub

End Class

As you have learned, that does not work. WinForms are event driven. If you want to handle a click event you have to define the event handler either by attaching the "Handle control.Click" command to the method definition or by using an addhandler statement for each control.

Give this a try. It will attach a Click event handler for all PictureBoxes on the form.

Public Class Form1

   Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
      AddPBClickHandlerToAllPictureBoxesParentByTheFormOrItsChildControls(Me)
   End Sub

   Private Sub AddPBClickHandlerToAllPictureBoxesParentByTheFormOrItsChildControls(ByVal cnrl As Control)
      ' Designed to Initially be passed a Form Control instance
      For Each c As Control In cnrl.Controls
         If TypeOf c Is PictureBox Then
            AddHandler c.Click, AddressOf PictureBox_Click
         End If
         If c.HasChildren Then AddPBClickHandlerToAllPictureBoxesParentByTheFormOrItsChildControls(c)
      Next
   End Sub

   Private Sub PictureBox_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
      If TypeOf sender Is PictureBox Then
         CType(sender, PictureBox).BackColor = Color.Blue
      End If
   End Sub
End Class
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.