Handling a C# event from VB.NET

D

Dave

I have the following code. I am trying to handle the event in the C#
code in VB.net. However whenever the event tries to get called, the
MyEvent method is always null..... any ideas?

VB.NET
dim xml as new MyClass
AddHandler xml.MyEvent, New EventHandler(AddressOf xmlEvent)

C#
public class XMLHandler
{
public event EventHandler MyEvent;

protected virtual void OnRaiseMe(object o, EventArgs e)
{
if (MyEvent!=null)
MyEvent(this, e); //Doesn't happen as MyEvent is null
}
}
 
L

Larry Lard

Dave said:
I have the following code.
Really?

I am trying to handle the event in the C#
code in VB.net. However whenever the event tries to get called, the
MyEvent method is always null..... any ideas?

VB.NET
dim xml as new MyClass
AddHandler xml.MyEvent, New EventHandler(AddressOf xmlEvent)

You haven't defined MyClass (you call your C# class 'XMLHandler', and
in fact 'MyClass' is a VB.NET keyword, so this line can't even
compile. You also don't show us xmlEvent.

This code works for me in VS2003:

In a C# class library (this is your code with the addition of a public
method that raises the event):

using System;

namespace ClassLibrary1
{
/// <summary>
/// Summary description for Class1.
/// </summary>
public class XMLHandler
{
public event EventHandler MyEvent;

public void RaiseE()
{
OnRaiseMe(null, null);
}

protected virtual void OnRaiseMe(object o, EventArgs e)
{
if (MyEvent!=null)
MyEvent(this, e); //Doesn't happen as MyEvent is null
}


}
}

In a VB.NET Windows Forms application with a reference to the above:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click

Dim x As ClassLibrary1.XMLHandler

x = New ClassLibrary1.XMLHandler

AddHandler x.MyEvent, AddressOf Me.MyEventHandler

x.RaiseE()
End Sub

Public Sub MyEventHandler(ByVal o As Object, ByVal e As EventArgs)
MsgBox("pop")
End Sub

Click the button, up comes the message box.
 
S

Stoitcho Goutsev \(100\) [C# MVP]

Dave,

The problem is not in the code you've posted. Even though I was sure I've
tested it and it works.

The only reason of this to happen that I can think of from the top of my
head is if you re-create the XMLHandler object after you attach the event
handler.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

How can these lines be rewritten 15
Delegates and Events 8
Event Subscription. Why? 8
struggling with events 4
Delegates/events 8
Raising and event 3
Events and Thread Safety 5
Object garbage collection of events 8

Top