Passing AddressOf a function to constructor

  • Thread starter Thread starter David A. Osborn
  • Start date Start date
D

David A. Osborn

I need to pass the address of a function to the contructor of a class when I
create an instance of it so that in the new instance I can dynamically
hookup a handler by doing the following:

AddHandler ButtonNew.Click, AddressOf My_Passed_Function

I thought I could use a delegate but that doesn't seem to be working. Am I
on the right track?
 
David,
You need to define your parameter as the type of handler you are going to
use, when you call your function/constructor you use addressof, when you
call AddHandler you can use the parameter (as its already has the addressof
something.

Something like:

Public Class Widget

Public Sub New(ByVal theHandler As EventHandler)
Dim ButtonNew As New Button
AddHandler ButtonNew.Click, theHandler
End Sub

End Class

Public Sub Widget_Click(ByVal sender As Object, ByVal e As EventArgs)

End Sub

Dim aWidget As New Widget(AddressOf Widget_Click)

You can find out the type of handler (Delegate) needed by looking up the
event in the online help.

Hope this helps
Jay
 
David,

Why not passing the control itself so. Something as

\\\
Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Button1.Text = "0"
Dim mb As New myButtonClass(Me.Button1)
End Sub
End Class
Friend Class myButtonClass
Friend Sub New(ByVal this As Control)
AddHandler this.Click, AddressOf ButtonClick
End Sub
Private Sub ButtonClick(ByVal sender As System.Object, _
ByVal e As System.EventArgs)
Dim mybutton As Button = DirectCast(sender, Button)
mybutton.Text = (CInt(mybutton.Text) + 1).ToString
End Sub
End Clas
///
I hope this gives some ideas

Cor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top