e.Data.GetData casting problem in WinForms drag-and-drop

微笑、不失礼 提交于 2019-12-10 20:57:18

问题


i'm trying to make a drag-and-drop between 2 instances of my programs, but when i try to cast data to my type it throws an Invalid Cast Exception.

Here is the code:

    protected virtual void GetDropIEntities(DragEventArgs e)
    {

        foreach (string s in e.Data.GetFormats())
            Console.WriteLine(s);

        Entity[] myDroppedEnts = (Entity[])e.Data.GetData(e.Data.GetFormats()[0]);

    }

The weirdest thing is that Console.WriteLine writes "Entity[]" on the output, but when i try to cast the exception is thrown. Can someone give me a hand with this? Thx in advance!


回答1:


To drag and drop objects from one instance of an application to another, the object must be serializable. Otherwise, the cast will not work as expected.

To accomplish this, you can add the [Serializable] attribute to your Entity class, and optionally implement the ISerializable interface. For an introduction on how to make a class Serializable, see: http://msdn.microsoft.com/en-us/library/4abbf6k0(v=VS.90).aspx

This is the same issue with using the Clipboard. A great example can be seen on this CodeProject site:

http://www.codeproject.com/KB/cs/copycustomclasstoclipbrd.aspx



来源:https://stackoverflow.com/questions/7122987/e-data-getdata-casting-problem-in-winforms-drag-and-drop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!