Search code examples
c#winformsdrag-and-drop

How to deal with GetDataPresent to let it accept all the derived types


I'm using drgevent.Data.GetDataPresent to determine whether the dragged component is acceptable or not.

I've got a problem which is that I want to accept a specific type say SomeType and all the types that derived from it. Seems GetDataPresent doesn't support such requirement.

Any idea?


Solution

  • Just don't use GetDataPresent(), it is boilerplate but you're free to do it your way. Actually retrieve the object and check if you're happy with its type:

        protected override void OnDragEnter(DragEventArgs drgevent) {
            var obj = drgevent.Data.GetData(drgevent.Data.GetFormats()[0]);
            if (typeof(Base).IsAssignableFrom(obj.GetType())) {
                drgevent.Effect = DragDropEffects.Copy;
            }
        }
    

    Where Base is the name of the base class. While the use of GetFormats() looks odd, this approach is guaranteed to work because dragging a .NET object only ever produces one format, the display name of the type of the object. Which is also the reason that GetDataPresent can't work for derived objects.