Search code examples
arraysvb.netpictureboxmouseclick-event

How do I ask for multiple Picturebox-Clickevents in VB


I have a 10x10 Array of Pictureboxes that the user needs to click and I'm obviously too lazy to write 100 single "Picturebox.Onclick"-Paragraphs, one for each Picturebox in the Array. What can I do?

The only way I know is to have one Paragraph for each Picturebox and I have done this for up to, like, 8 Pictureboxes. But for 100? Naaahhh. I know there has to be an easier way but I can't figure it out.


Solution

  • You can convert your array of picture boxes to a list then add an handler to the mouse click event of the items in the list. Like this

     Dim piclist As New List (Of PictureBox)
     'Convert 2d array to 1d array and store in a List
     '***********************
     ' Replace picarr with the name of your picture box array
     For x As Integer = 0 To 9
         For y As Integer = 0 To 9
             piclist.Items.Add(picarr(x,y)
         Next
     Next
     '*************************
    
     For Each item As PictureBox in piclist
          AddHandler item.Click, AddressOf picclick
     Next
    
     Public Sub picclick (sender As Object,  e As EventArgs)
         'Add actions here
     End Sub