How To Copy Data To Clipboard In C#

Learn how to copy data to clipboard in C# and read data back from the clipboard.

If you use CTRL+C, some data or files are copied to the system clipboard memory and when you use CTRL+V, the data is copied back to wherever you paste it. The Clipboard class provides functionality to place data to and retrieve data from the clipboard.
 
Storing and Retrieving Data
 
Clipboard has static methods to copy and paste data. The SetDataObject method is used to store data that is in object format to the clipboard. The following code snippet copies selected text from a RichTextBoc control to the clipboard. 
  1. Clipboard.SetDataObject(richTextBox1.SelectedText);  
The GetDataObject method reads data back from the clipboard. The following code snippet gets data from the clipboard and displays in a Label control.
  1. // Retrieves data  
  2. IDataObject iData = Clipboard.GetDataObject();  
  3. // Is Data Text?  
  4. if (iData.GetDataPresent(DataFormats.Text))  
  5. label1.Text = (String)iData.GetData(DataFormats.Text);  
  6. else  
  7. label1.Text = "Data not found.";  
  8. Clear Clipboard  
  9. Clear method removes all data from the Clipboard.  
  10. Clipboard.Clear();  
Summary
 
The Clipboard class provides methods to save to and retrieve data from system clipboard.