davearia Posted August 21, 2008 Posted August 21, 2008 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. Quote
Leaders snarfblam Posted August 21, 2008 Leaders Posted August 21, 2008 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. Quote [sIGPIC]e[/sIGPIC]
davearia Posted August 26, 2008 Author Posted August 26, 2008 I took the 2nd option on your recommendation and it works a treat. Thanks for your help mate.:D :D :D Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.