Javad Memariani Javad Memariani - 4 months ago 17
Vb.net Question

Keep address of sub in property

I'm going to use property to keep address of the click sub and then assign it to each button in AddRow() sub. The problem occurred when I got the following error:

Error 1 Method 'Public Property ClickEvent As Button_Click' does not have a signature compatible with delegate 'Delegate Sub EventHandler(sender As Object, e As System.EventArgs)'.

Private Sub Button_Click(sender As Object, e As EventArgs)
'do somthing
End Sub

Class CustomClass
Public Fields As New List(Of FieldsDefinition)()

Class FieldsDefinition
Public Delegate Sub Button_Click(sender As System.Object, e As System.EventArgs)

Public __ClickEventValue As Button_Click
Public Property ClickEvent() As Button_Click
Get
Return __ClickEventValue
End Get

Set(ByVal value As Button_Click)
__ClickEventValue = value
End Set
End Property
End Class

Public Sub AddRow()
For Each field As FieldsDefinition In Fields
Dim ctrl As New TextBox
AddHandler ctrl.Click, AddressOf field.ClickEvent
Next
End Sub
End Class

Answer

2 changes:

  1. Remove the AddressOf, as you don't want the handler to be the ClickEvent property itself, you want it to be the returned delegate.

  2. AddHandler will expect a handler of type EventHandler. So, remove the Button_Click delegate declaration, and replace any references to it by EventHandler.

Code:

Private Sub Button_Click(sender As Object, e As EventArgs)
    'do somthing
End Sub

Class CustomClass
    Public Fields As New List(Of FieldsDefinition)()

    Class FieldsDefinition
        ' removed Button_Click delegate declaration here

        Public __ClickEventValue As EventHandler 'changed Button_Click to EventHandler here
        Public Property ClickEvent() As EventHandler 'changed Button_Click to EventHandler here
            Get
                Return __ClickEventValue
            End Get

            Set(ByVal value As EventHandler) 'changed Button_Click to EventHandler here
                __ClickEventValue = value
            End Set
        End Property
    End Class

    Public Sub AddRow()
        For Each field As FieldsDefinition In Fields
            Dim ctrl As New TextBox
            AddHandler ctrl.Click, field.ClickEvent 'removed AddressOf here
        Next
    End Sub
End Class
Comments