0

I have mouse double click event on wpf data grid in code behind as follow:

async void dataGrid_MouseDoubleClick(object o, MouseButtonEventArgs e)
{
     var dg = (DataGrid)o;
     var item = (MyCustomType)dg.SelectedItem;
     await MyAsyncMethod(item.Id);
}

and on line

var dg = (DataGrid)o;

NullReferenceException occured. Morover, I have no way to show value during debugging session. When I change my method to:

async void dataGrid_MouseDoubleClick(object o, MouseButtonEventArgs e)
{
    if(o is DataGrid && (o as DataGrid).SelectedItem !=null)
    {
         await MyAsyncMethod(((MyCustomType)(o as DataGrid).SelectedItem).Id);
    }
}

everythings seems to work correctly. How async mouse double click works that I can not invoke event like first representation?

ElConrado
  • 1,477
  • 4
  • 20
  • 46

1 Answers1

2

The main difference between the first and second code snippet is that the first doesn't check whether there actually is a SelectedItem available.

Use the as operator like this and you should be fine:

async void dataGrid_MouseDoubleClick(object o, MouseButtonEventArgs e)
{
    var dg = (DataGrid)o;
    var item = dg.SelectedItem as MyCustomType;
    if (item != null)
        await MyAsyncMethod(item.Id);
}

Your issue has nothing to do with the event itself nor async/await.

Edit:

If MyCustomType is a struct you cannot use the as operator but you should still check whether the SelectedItem property is actually set:

async void dataGrid_MouseDoubleClick(object o, MouseButtonEventArgs e)
{
    var dg = (DataGrid)o;
    if (dg.SelectedItem != null)
    {
        await MyAsyncMethod(((MyCustomType)dg.SelectedItem)item.Id);
    }
}
mm8
  • 163,881
  • 10
  • 57
  • 88
  • Thanks for asyn/await part of the answer. Unfortunately if MyCustomType is struct than 'as' operator does not work. – ElConrado Mar 22 '18 at 11:36
  • That's true. But you should still check whether the SelectedItem != null like you do in your second snippet. – mm8 Mar 22 '18 at 12:31