Fabrizio Leoncini
Fabrizio Leoncini

Reputation: 39

How to add an event handler in VB.NET?

This code is part of AjaxControlToolkitSampleSite. To be exact, it is in the AsyncFileUpload control:

 AsyncFileUpload1.UploadedComplete += new EventHandler<AsyncFileUploadEventArgs>(AsyncFileUpload1_UploadedComplete);

How can I translate this to VB.NET?

Upvotes: 2

Views: 4764

Answers (4)

avanek
avanek

Reputation: 1659

Two ways to do this:

If your AsyncFileUpload1 variable has the WithEvents qualifier, you can do the following using the Handles keyword on the event handler itself:

Private Sub AsyncFileUpload1_UploadedComplete(ByVal sender As Object, ByVal e As AsyncFileUploadEventArgs) Handles AsyncFileUpdate1.UploadedComplete

    'handler logic...

End Sub

If there is no WithEvents qualifier, then the following works:

AddHandler AsyncFileUpload1.UploadedComplete, AddressOf AsyncFileUpload1_UploadedComplete

To remove the event handler, do the following:

RemoveHandler AsyncFileUpload1.UploadedComplete, AddressOf AsyncFileUpload1_UploadedComplete

Beware of the WithEvents/Handles route as this can cause memory leaks. It is simply syntactic sugar and wires up an AddHandler behind the scenes. I add this because I've been burned before with it while learning VB (I had a C# background).

Upvotes: 0

Heinzi
Heinzi

Reputation: 172380

Others have shown how to literally translate event+= to AddHandler in VB.

However, despite the similarities, VB and C# are different languages, and good C# code might not be good VB code when translated literally. For example, in VB, the canonical way to attach a fixed event handler to an ASP.NET control is by using the Handles keyword:

Protected Sub AsyncFileUpload1_UploadedComplete(sender As Object, _
                                                e As AsyncFileUploadEventArgs) _
    Handles AsyncFileUpload1.UploadedComplete

    ' Your event handler code is here

End Sub

Upvotes: 1

Justin Dearing
Justin Dearing

Reputation: 14948

If you can put that code in a C# project that compiles, you can convert that project to VB.NET with SharpDevelop. This is probably the best way to translate between C# and VB.NET.

Also, ILSpy can translate a compiled dll written in C# into VB.NET

Upvotes: 0

competent_tech
competent_tech

Reputation: 44941

Here you go:

AddHandler AsyncFileUpload1.UploadedComplete, AddressOf AsyncFileUpload1_UploadedComplete

Alternatively, within your code, you can select the AsyncFileUpload1 control from the left-hand dropdown list (just above the code) and then select the UploadComplete event from the right-hand dropdown list.

This will automatically create an event handler with the correct signature using the VB Handles declaration.

Upvotes: 7

Related Questions