user1035909
user1035909

Reputation: 83

Null Reference exception of an event

I am using a WPF c# application. I have a user control which contains a datagrid. I am trying to send a public event from the user control , on a right mouse click. Here is the created public event

public event MouseButtonEventHandler datagridMouseClick;

Next its supposed to be fired on this event handler of the datagrid:

private void dataGrid1_MouseDown(object sender, MouseButtonEventArgs e)
{
    DependencyObject dep = (DependencyObject)e.OriginalSource;
    while ((dep != null) &&
    !(dep is DataGridCell) &&
    !(dep is DataGridColumnHeader))
    {
        dep = VisualTreeHelper.GetParent(dep);
    }
    if (dep is DataGridCell)
    {
        cell = dep as DataGridCell;
        while ((dep != null) && !(dep is DataGridRow))
        {
            dep = VisualTreeHelper.GetParent(dep);
        }
        row = dep as DataGridRow;
    }

    this.datagridMouseClick(sender, e);  // GIVING ERROR
}

It gives me a NullReferenceException. Can u help me figure out why. Thanks in advance, any help appreciated regards

The event is handled in another class (another project actually since the above is a dll apart) .. So its listened when the other class is initialized here..

public Window1()
    {
       InitializeComponent();      
        search.datagridDoubleClick +=new RoutedEventHandler(search_datagridDoubleClick);
        search.datagridMouseClick += new MouseButtonEventHandler(search_datagridMouseClick); /* Only this one gives error , even if the other one is handled exactly the same way in the code o.O */

    }

Where search is the name of the object that contains the above 1st code

I think the problem here is that i am trying to listen to an event fired from another class/project (since the first code is from a .dll) that way the current class doesnt initialize a listener and keeps it to null. eventhough i have used this EXACT method on search.datagridDoubleClick above and works perfectly (thats weird). PS. i dont get the -1 , sounds like a valuable question to me, anyways...

Upvotes: 0

Views: 4774

Answers (1)

MBen
MBen

Reputation: 3996

You need to check if somebody subscribed to your event by checking if datagridMouseClick is different from Null.

if (datagridMouseClick != null)
    this.datagridMouseClick(sender, e);

Upvotes: 4

Related Questions