Copy and Paste in C# .NET

Copy and Paste in C# .NET

To Copy something to the Clipboard, you highlight text and click a Copy item on an Edit menu. Once the data is copied to the Clipboard, it can be Pasted elsewhere. We'll implement this with our menu system.
Double click the Copy item on your Edit menu. You'll be taken to the code stub for your Copy menu item. Add the following code between the curly brackets:
textBox1.Copy();
Using the Copy method of text boxes is enough to copy the data on to the Windows Clipboard. But you can first check to see if there is any highlighted text to copy. Change your code to this:
if (textBox1.SelectionLength > 0)
{

textBox1.Copy();
}
We're using an if statement again. This time, we are checking the SelectionLength property of text boxes. The length returns how many characters are in the text that was selected. We want to make sure that it's greater than zero.
We'll use the second text box to Paste. So access the code stub for your Paste menu item, using the same technique as before. Add the following between the curly brackets of your Paste code:
textBox2.Paste();
Notice that we're now using textBox2 and not textBox1. After the dot, you only need to add the Paste method.
Try your Edit menu out again. Highlight the text in the first text box. Click Edit > Copy. Now click into your second text box and click Edit > Paste.
You can also check to see if there is any data on the Clipboard, and that it is text and not, say, an image. Add this rather long if statement to your code:
if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text) == true)
{

textBox2.Paste();
Clipboard.Clear();

}
Getting at the data on the Clipboard can be tricky, but we're checking to see what the DataFormat is. If it's text then the if statement is true, and the code gets executed. Notice the last line, though:
Clipboard.Clear();
As you'd expect, this Clears whatever is on the Clipboard. You don't need this line, however, so you can delete it if you prefer. See what it does both with and without the line.

In the next part, we'll code for the View menu.

Comments