XperSona XperSona - 5 months ago 47
Vb.net Question

onClick Event For Picturebox

I have more than 30 picture box in a windows form named

PictureBox1
PictureBox2
PictureBox3
.....so on


I am having to write the same procedure for click function for every single one of them.
I just want to be able to write a single handler that would handle the click events for all the PictureBox and call the same function.




For a rough technical example.. Sorry for the JavaScript Format




picturebox.onclick(){
var a=get_index(this); //gets address of the clicked picturebox
somefunction(a);
}

Answer

If you are using the Handles keyword, which is the default, typical way to handle events from controls, you can add multiple event names to the Handles clause, for instance:

Private Sub OnClick(sender As Object, e As EventArgs) Handles PictureBox1.Click, PictureBox2.Click, PictureBox3.Click
    ' Handles click events from PictureBox1, PictureBox2, and PictureBox3
End Sub

Alternatively, you can declare the event handler method without the Handles clause, and then manually attach it to the events yourself, like this:

Private Sub OnClick(sender As Object, e As EventArgs)
    ' ...
End Sub

' ...

AddHandler PictureBox1.Click, AddressOf OnClick
AddHandler PictureBox2.Click, AddressOf OnClick
AddHandler PictureBox3.Click, AddressOf OnClick

Or, if you have list of picture box controls, you could add the event handlers in a loop, like this:

Dim myPictureBoxes() As PictureBox = {PictureBox1, PictureBox2, PictureBox3}
For Each i As PictureBox in myPictureBoxes
    AddHandler i.Click, AddressOf OnClick
Next

Or, you could access them from your form's Controls collection by name:

For i As Integer = 1 to 30
    Dim c As Control = Me.Controls("PictureBox" & i.ToString())
    AddHandler c.Click, AddressOf OnClick
Next

Bear in mind, however, if you do manually call AddHandler, you need to also call RemoveHandler to later detach the event handler.

It seems odd, on the surface, to have so many picture boxes like that, though. You may want to consider custom-drawing your content in a single control or look into dynamically loading the controls at run-time.