Search code examples
vb.netevent-handlingcontrol-array

How to Handle events from a control array VB.net


To start, hi to everyone im new to stackoverflow, and also new to programing (on 1º year). I've been searching but ive found nothing that answer my question, or maybe im just to newbie to understand the answers, so im sorry if its too simple, i cant see it!

/* my native lenguage is not english*/

Here is my problem, i'm making a VB form whit 200 pictureboxes that have to change or interact on click

i've made a control array whit all of them, like this:

Dim control(199) As PictureBox = Controles(control, 0)


Function Controles(ByRef control As Array, ByVal cont As Integer)

    For Each pic As PictureBox In Me.Controls

        control(cont) = pic
        cont += 1

    Next
    Return control
End Function

this should asociate each picturebox to an array position, my problem now is how i can set the event handler to watch at control().click so no matter what box you click the event onclick will proc.

the only way i know is to create a click handler for each box manually.

hope i can find some answers


Solution

  • Using the Addhandler statement you can wire them all to the same routine. Then cast the sender object to interact with the PB that was clicked. OfType function.

    Private Sub LoadME() Handles Me.Load
     For Each pb As PictureBox In Me.Controls.OfType(Of PictureBox)()
      'add all PB click events to a event sub
      AddHandler pb.Click, AddressOf pb_Click
     Next
    End Sub
    
    Private Sub pb_Click(sender As Object, e As EventArgs)
      Dim pb = DirectCast(sender, PictureBox)
      'this is the PB that was clicked
    End Sub