Problems in VB.net with delegates.

Posted on Updated on

I’m C# developer working in a VB.net project and as everybody said, if you know C# you won’t have any problems with VB. Well this hasn’t been 100% in my case (probably a 98%).

There are some annoyances in VS that drive me crazy like the fact that reorganises the code automatically when I press enter or when I add something in a multiple line sentence it removes all my indentation (bloody _ )

Recently I came across another issue with VB, the events.

The environment: ASP.net, AJAX… and VB, of course.

I created a user control called “RequestSearchControl” and I added an event called “RequestSelected“.


Partial Public Class RequestSearchControl

Inherits UserControl

Public Event RequestSelected(ByVal requestID As Integer)


Private Sub SelectRow(ByVal rowIndex As Integer)

RaiseEvent RequestSelected(rowIndex)

End Sub


End Class

Good, everything compiles!

Then I used my brand new user control in a Page


<
td>

<uc1:RequestSearchControl ID=”ParentRequestSearch”

runat=”server”

OnRequestSelected=”ParentRequestSearch_RequestSelected” />

</td>

and I added the handler in the code (I added the handler in the markup, in the code and in the OnLoad using AddHandler just in case…)

Partial Public Class RequestEditControl

Inherits UserControl


Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

AddHandler ParentRequestSearch.RequestSelected, AddressOf ParentRequestSearch_RequestSelected

End Sub



Protected Sub ParentRequestSearch_RequestSelected(ByVal requestID As Long) Handles ParentRequestSearch.RequestSelected

‘ Do Something


End Sub

End Class

Good again, everything compiles! Again! I’m on the good track!

But then… nothing happened!


Note:

When I say nothing I mean, NOTHING! No compile errors, no exceptions and it executes the code that should raise the event, and nothing.

After a number of nothing-happening-trials I thought, “Why don’t I add a delegate as I would have done it in c#?

I added:

Public Delegate Sub RequestSelectedDataHandler(ByVal requestID As Integer)

and I changed the event definition:

Public Event RequestSelected As RequestSelectedDataHandler

And… Voila! all the events worked.

Why didn’t the compiler or the runtime complain? I don’t know but it really didn’t make me think any better about VB...

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s