Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine data type from DragEventArgs

I have implemented drag and drop in my application, but am having some difficulty determining the type of the object being dragged. I have a base class Indicator and several classes derived from it. A dragged object could be of any of these types. The code snippet below seems inelegant and is prone to maintenance issues. Every time we add a new derived class, we have to remember to touch this code. It seems like we should be able to use inheritance here somehow.

  protected override void OnDragOver(DragEventArgs e)
  {
     base.OnDragOver(e);

     e.Effect = DragDropEffects.None;

     // If the drag data is an "Indicator" type
     if (e.Data.GetDataPresent(typeof(Indicator)) ||
         e.Data.GetDataPresent(typeof(IndicatorA)) ||
         e.Data.GetDataPresent(typeof(IndicatorB)) ||
         e.Data.GetDataPresent(typeof(IndicatorC)) ||
         e.Data.GetDataPresent(typeof(IndicatorD)))
     {
        e.Effect = DragDropEffects.Move;
     }
  }

Similarly, we have issues using GetData to actually get the dragged object:

protected override void OnDragDrop(DragEventArgs e)
{
    base.OnDragDrop(e);

    // Get the dragged indicator from the DragEvent
    Indicator indicator = (Indicator)e.Data.GetData(typeof(Indicator)) ??
                          (Indicator)e.Data.GetData(typeof(IndicatorA)) ??
                          (Indicator)e.Data.GetData(typeof(IndicatorB)) ??
                          (Indicator)e.Data.GetData(typeof(IndicatorC)) ??
                          (Indicator)e.Data.GetData(typeof(IndicatorD));
}

Thanks.

like image 882
NascarEd Avatar asked Jun 30 '10 14:06

NascarEd


2 Answers

Store your data by explicitly specifying the type, i.e.

dataObject.SetData(typeof(Indicator), yourIndicator);

This will allow you to retrieve it just based on the Indicator type, rather than the child type.

like image 116
Adam Robinson Avatar answered Nov 11 '22 21:11

Adam Robinson


There's the IDataObject.GetFormats method:

Returns a list of all formats that data stored in this instance is associated with or can be converted to.

It's an array of String:

String[] allFormats = myDataObject.GetFormats();

You could then check that list for your type, one of which should be Indicator I would have thought.

like image 28
ChrisF Avatar answered Nov 11 '22 20:11

ChrisF