Bennett
Bennett

Reputation: 738

How can I cut text from textbox and copy to clipboard?

Let me begin by saying I am a beginner programmer and I know my last code statement is incorrect. I am writing a notepad application and I can't quite figure out how to cut text. I know that when you cut text all you are doing is copying the selected text to the clipboard, and then deleting the selected text. As I said I know the syntax is wrong I'm just trying to show what I'm attempting to do.

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            textBox1.Text = Clipboard.GetText(); // will paste whatever text is copied to clipboard
        }
        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(textBox1.SelectedText);//copies whatever text is selected in my textbox
        }
        private void clearClipboardToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Clipboard.Clear();//clears clipboard
        }
        private void cutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(textBox1.SelectedText);
            textBox1.SelectedText == "";//line I know is incorrect
        }

Upvotes: 1

Views: 3318

Answers (3)

Rattlefire
Rattlefire

Reputation: 39

In CompactFramework we do not have TextBox.SelectedText.Copy() method, but we can use public static class Clipboard:

TextBox1.SelectAll();
if (TextBox1.SelectionLength > 0)
{
    Clipboard.SetDataObject(TextBox1.SelectedText);
}

Upvotes: 0

Peter Duniho
Peter Duniho

Reputation: 70671

The best way to do this is to just delegate the operation to the TextBox:

Cut
Copy
Paste

That said, if you want to do it manually, the problem with your line of code is that you are using the == operator instead of the = operator. The code you wrote would work, using the correct operator. :)

Note that textBox1.SelectedText = Clipboard.GetText(); would be a more typical "paste" implementation. There's nothing wrong with replacing the entire text box's text if that's really what you mean to do, but it could surprise some users.

Upvotes: 3

jmcilhinney
jmcilhinney

Reputation: 54417

The TextBox has its own Cut, Copy and Paste methods. This is exactly why you should read the documentation first. Not surprisingly, the documentation for the TextBox class lists those methods.

Upvotes: 0

Related Questions