[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Copy and paste objects to the clipboard in C#

Copy and paste objects to the clipboard

It's pretty easy to copy and paste objects to the clipboard in C#. The only real trick is to decorate the class that you want to use with the Serializable attribute. That allows the clipboard to serialize and deserialize instances of the class. The following code shows this example's Person class.

[Serializable()] class Person { public string FirstName; public string LastName; }

The following code shows how the program copies a Person object to the clipboard.

// Copy a Person to the Clipboard. private void btnCopy_Click(object sender, EventArgs e) { Person person = new Person() { FirstName = txtFirstName.Text, LastName = txtLastName.Text }; Clipboard.SetDataObject(person); }

This code uses the values in the program's text boxes to create a new Person object. It then simply calls the Clipboard object's SetDataObject method.

The following code shows how the program pastes a Person object from the clipboard.

// Paste the person from the Clipboard. private void btnPaste_Click(object sender, EventArgs e) { IDataObject data_object = Clipboard.GetDataObject(); if (data_object.GetDataPresent( "howto_clipboard_objects.Person")) { Person person = (Person)data_object.GetData( "howto_clipboard_objects.Person"); txtDropFirstName.Text = person.FirstName; txtDropLastName.Text = person.LastName; } else { txtDropFirstName.Clear(); txtDropLastName.Clear(); } }

First the code uses the GetDataPresent method to see if the clipboard is holding an object of the correct type. Notice that the object's type name includes its namespace.

If there is an object of the right class present, the program uses the Clipboard object's GetData method to get it. The result has the plain Object type, so the code casts it into a Person object.

Download the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.