Back to Devexpress

How to: Paste Clipboard's Text to TextBox Control

windowsforms-9526-controls-and-libraries-editors-and-simple-controls-examples-how-to-paste-clipboards-text-to-textbox-control.md

latest1.8 KB
Original Source

How to: Paste Clipboard's Text to TextBox Control

  • Oct 25, 2019

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.

csharp
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();
}
vb
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles Button1.Click
    If Clipboard.GetDataObject().GetDataPresent("System.String") = True Then
        If TextEdit1.SelectionLength > 0 Then
                If MessageBox.Show("Do you want to paste over current selection?", 
                  "Paste Example", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) = _
                  DialogResult.No Then
                TextEdit1.SelectionStart = TextEdit1.SelectionStart + TextEdit1.SelectionLength
                TextEdit1.SelectionLength = 0
            End If
        End If
        TextEdit1.Paste()
    End If
End Sub