Adding Handler Manually RRS feed

  • Question

  • Hey,

    I have a form with a button in it, on the button click a picturebox is created in wich its tag property contains a random number.

    What I want is to, using code, add handler to the newly created picturebox mousedown event and when the event is raised I want a messagebox displaying the number contained in its tag.

    Any help would be appreciated...

    Tuesday, January 14, 2014 3:14 PM


All replies

  • There are thousand of samples around this.

    One of them on our website.


    The code in the load event goes in your program inside the buttonclick method which handles the click


    • Marked as answer by Hadi Ayash Tuesday, January 14, 2014 3:30 PM
    Tuesday, January 14, 2014 3:20 PM
  • Get the tag from the "Sender" object that you will have casted to a pictureBox

    Public Class Form1
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim PB As New PictureBox With {.Parent = Me, .BackColor = Color.Black}
            PB.Tag = 123
            AddHandler PB.MouseDown, AddressOf PB_Mousedown
        End Sub
        Private Sub PB_Mousedown(ByVal s As Object, ByVal e As EventArgs)
            Dim PB As PictureBox = DirectCast(s, PictureBox)
            Dim TagValue As String = PB.Tag.ToString
        End Sub
    End Class

    • Proposed as answer by IronRazerz Tuesday, January 14, 2014 3:32 PM
    Tuesday, January 14, 2014 3:31 PM
  • Thanks Cor and Crazypennie
    Tuesday, January 14, 2014 3:33 PM
  • Hello,

    I would go with CrazyPennie's reply. The following can also be done via VS2010 or higher with a caveat, the event can not be unsubscribed with RemoveHandler.

     AddHandler PictureBox1.MouseDown,
         Sub(s As Object, ea As EventArgs)
             Dim pBox As PictureBox = DirectCast(s, PictureBox)
         End Sub

    And in C#

    pictureBox1.MouseDown += (object sender, MouseEventArgs e) =>
            PictureBox pBox = (PictureBox)sender;

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.

    Tuesday, January 14, 2014 3:40 PM