Handling a C# event from VB.NET

  • Thread starter Thread starter Dave
  • Start date Start date
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
}
}
 
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.
 
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.
 
Back
Top