Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Hi,

 

I am creating an instance of a control within my form programatically like so:

Private Sub SetUp()
   For Each r As DataRow In dvFilter.ToTable.Rows
       Dim o As New ctlMachine(sPath, r)
   Next
End Sub

Within this control there is this event:

Private Sub PictureBox1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseClick
   RaiseEvent MouseClicked(dr)
End Sub

This in turn is handled by this event declaration in the same control:

Public Event MouseClicked(ByVal r As DataRow)

 

But I am struggling to reference this event at form level.

 

How do I wire this event up to the form?

 

Cheers, Dave.

  • Leaders
Posted

There are two ways to wire events at runtime: WithEvents and AddHandler.

 

WithEvents looks neater in code and VB takes care of most of the work, but it requires a special pre-defined variable. It would be done like so:

Private WithEvents PictureBox SomePictureBox

Sub SomeEventHandler(sender As Object, e As EventArgs) Handles SomePictureBox.Click
   'Do some stuff
End Sub

Sub ExampleCode()
   'When we assign a picturebox to this variable the event is automatically wired.
   SomePictureBox = new PictureBox()
   'The event is automatically unwired when another picture box or Nothing is assigned to the variable

   Controls.Add(SomePictureBox)
End Sub

 

The AddHandler method can be much more dynamic and is more consistent with other languages, but takes more work and is less structured.

Sub SomeEventHandler(sender As Object, e As EventArgs)
   'Do some stuff
End Sub

Sub ExampleCode()
   Dim SomePictureBox As New PictureBox()
   Controls.Add(SomePictureBox)

   'We manually wire the event here.
   AddHandler SomePictureBox.Click, AddressOf SomeEventHandler
   'To unwire the event, we would use the RemoveHandler statement.
End Sub

You can use either method to wire any event to a handler declared in your form. In your case you probably want to go with AddHandler.

[sIGPIC]e[/sIGPIC]

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...