Priyank Thakkar
Priyank Thakkar

Reputation: 4852

Putting the object of userdefined type on clipboard and retriving it

I am having a class Student. I want to store the object of class Student 'objStu' on the clipboard.

Class Student
{
    string stuID;
    string Name;
    string email;
}

In the main method I wrote a code:

Clipboard.SetDataObject(objStu,false);

When I tried to retrive the object as below:

Student anotherStu = Clipboard.GetDataObject() as Student;

It is returning null. Please guide me how to achieve it.

Upvotes: 0

Views: 327

Answers (1)

Damith
Damith

Reputation: 63065

make Student class as Serializable

[Serializable]
public class Student
{
    public string stuID { get; set; }
    public string Name { get; set; }
    public string email { get; set; }
    public void CopyToClipboard()
    {

        DataFormats.Format format =
             DataFormats.GetFormat(typeof(Student).FullName);
        //now copy to clipboard
        IDataObject dataObj = new DataObject();
        dataObj.SetData(format.Name, false, this);
        Clipboard.SetDataObject(dataObj, false);

    }

then you try as:

Student objStu = new Student();
objStu.Name = "test";
objStu.CopyToClipboard();
Clipboard.SetDataObject(objStu, false);
Student anotherStu = GetFromClipboard();

below is the GetFromClipboard method

protected static Student GetFromClipboard()
{
    Student student = null;
    IDataObject dataObj = Clipboard.GetDataObject();
    string format = typeof(Student).FullName;

    if (dataObj.GetDataPresent(format))
    {
        student = dataObj.GetData(format) as Student;
    }
    return student;
}

Check this link for more information

Upvotes: 2

Related Questions