AddressOf in Visual Basic .NET

Alph picture Alph · Aug 18, 2011 · Viewed 14.5k times · Source

I have buttons generated through code (dynamically). I have to associate an event (the same) to them. I use AddHandler button.click, AddressOf mysub.

The issue is that mysub gets a string (mysub(string)), but AddressOf doesn't accept a parameter inside the routine. How can I do this? Using also an alternative to AddressOf.

Public Class Form1

   ...

   Private Sub mysub(ByVal sender As Object, ByVal e As System.EventArgs, ByVal str As String)
      ...
      ...
   End Sub

   ...

   Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

      ...

      While something
         ...
         Dim btn As New Button
         ...
         AddHandler btn.click, AddressOf mysub 'here the issue
      End While

      ...

   End Sub
End Class

Answer

JaredPar picture JaredPar · Aug 18, 2011

It sounds like you have the following scenario

Class MyClass
  Public button As Button

  Public Sub New() 
    AddHandler button.Click AddressOf MySub
  End Sub

  Public Sub MySub(p As String)

  End Sub

End Class

If that's the case then you have a couple of options. The simplest is to use a helper method. Have it be the event handler and then call the MySub function

  Public Sub New() 
    AddHandler button.Click AddressOf MyHelper
  End Sub

  Public Sub MyHelper(sender As Object, e As EventArgs)
    MySub(TheStringValue)
  End Sub

EDIT

After talking with OP the problem is passing a local from the Form1_Load function into the MySub method. If you're using Visual Studio 2010 the easiest way to do this is with a Sub lambda expression

Dim theString = ...
AddHandler button.Click (Sub (sender, e) MySub(sender, e))

If your using an earlier version of Visual Studio it's a bit harder because you need to manually build up a closure.

Class Closure 
  Public TheForm as Form1
  Public TheString As String
  Public Sub OnClick(sender As Object, e As EventArgs)
    TheForm.MySub(sender, e)
  End Sub
End Class

...

' In Form1_Load
Dim closure As New Closure
closure.TheForm = Me
closure.TehString = get the string 

AddHandler button.Click AddressOf closure.OnClick