0

I am getting an error 'Object reference not set to an instance of an object. while dropping a dynamically created object in a grid.. the error occurring in below code

private void Control_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)       
{
    isDragging = false;
    var draggable = sender as UserControl;
    draggable.ReleaseMouseCapture();
}

need your great help.. thanks

Xaruth
  • 4,034
  • 3
  • 19
  • 26
  • @CodeCaster I disagree with this close vote. It is not the same thing – David Pilkington Oct 09 '14 at 09:00
  • @David the source of this issue is explained in that duplicate, as well as various hints on how to fix it. There is not enough information in this question to solve it, OP needs to read that one. Besides, your answer repeats a tiny fraction of the accepted answer in the duplicate. – CodeCaster Oct 09 '14 at 09:01

2 Answers2

2

When you use this

var draggable = sender as UserControl;

and it cannot perform the cast, the result is null.

If you use this cast, make sure to have a null check in case

David Pilkington
  • 13,528
  • 3
  • 41
  • 73
0

Check the msdn reference for "as" operator: http://msdn.microsoft.com/en-us/library/cscsdfbt.aspx

{

    isDragging = false;
    var draggable = sender as UserControl;
    if(draggable != null)
        draggable.ReleaseMouseCapture();
}

In case the cast is not succesful, it returns null.

blfuentes
  • 2,731
  • 5
  • 44
  • 72