Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AddressOf with parameter

Tags:

vb.net

One way or another I need to link groupID (and one other integer) to the button I am dynamically adding.. any ideas?

What I can do;

AddHandler mybutton.Click, AddressOf PrintMessage

Private Sub PrintMessage(ByVal sender As System.Object, ByVal e As System.EventArgs)
    MessageBox.Show("Dynamic event happened!")
End Sub

What I can't do, but want to;

AddHandler mybutton.Click, AddressOf PrintMessage(groupID)

Private Sub PrintMessage(ByVal groupID as Integer)
    MessageBox.Show("Dynamic event happened!" & groupID .tostring)
End Sub
like image 646
natli Avatar asked Feb 04 '12 18:02

natli


2 Answers

There is no way to do this with AddressOf itself. What you're looking for is a lambda expression.

AddHandler myButton.Click, Function(sender, e) PrintMessage(groupId)

Private Sub PrintMessage(ByVal groupID as Integer)
    MessageBox.Show("Dynamic event happened!" & groupID .tostring)
End Sub
like image 182
JaredPar Avatar answered Sep 19 '22 05:09

JaredPar


You can create your own button class and add anything you want to it

Public Class MyButton
    Inherits Button

    Private _groupID As Integer
    Public Property GroupID() As Integer
        Get
            Return _groupID
        End Get
        Set(ByVal value As Integer)
            _groupID = value
        End Set
    End Property

    Private _anotherInteger As Integer
    Public Property AnotherInteger() As Integer
        Get
            Return _anotherInteger
        End Get
        Set(ByVal value As Integer)
            _anotherInteger = value
        End Set
    End Property

End Class

Since VB 2010 you can simply write

Public Class MyButton
    Inherits Button

    Public Property GroupID As Integer

    Public Property AnotherInteger As Integer
End Class

You can access the button by casting the sender

Private Sub PrintMessage(ByVal sender As Object, ByVal e As EventArgs)
    Dim btn = DirectCast(sender, MyButton)
    MessageBox.Show( _
      String.Format("GroupID = {0}, AnotherInteger = {1}", _
                    btn.GroupID, btn.AnotherInteger))
End Sub

These new properties can even be set in the properties window (under Misc).

The controls defined in the current project automatically appear in the toolbox.

like image 44
Olivier Jacot-Descombes Avatar answered Sep 23 '22 05:09

Olivier Jacot-Descombes