How to: Paste Clipboard's Text to TextBox Control

The following code pastes text from the Clipboard to a TextEdit control. The text is pasted only if the Clipboard contains data in text format.

If the text editor contains selected text before pasting, a message box appears asking about overriding the selection. If the end-user presses the No button, the text from the Clipboard is inserted at the end of the selection. Otherwise, the text is pasted over the selection.

private void button1_Click(object sender, System.EventArgs e) {
    if (Clipboard.GetDataObject().GetDataPresent("System.String") == true) {
        if (textEdit1.SelectionLength > 0) {
            if (MessageBox.Show("Do you want to paste over current selection?",
              "Paste Example", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) ==
                DialogResult.No) {
                textEdit1.SelectionStart += textEdit1.SelectionLength;
                textEdit1.SelectionLength = 0;
            }
        }
    }
    textEdit1.Paste();
}