How to add an event handler in VB.NET? [closed]

帅比萌擦擦* 提交于 2019-12-18 08:58:13

问题


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?


回答1:


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.




回答2:


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



回答3:


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




回答4:


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).



来源:https://stackoverflow.com/questions/8840985/how-to-add-an-event-handler-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!