Search code examples
c#clipboard

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
        }

Solution

  • 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.