Winforms DataGridView copy / paste selected text

Andrzej K 31 Reputation points
2022-07-22T07:45:25.047+00:00

Hello. I have DataGridView with text column, that user will be able to edit text in it, and would like to implement Cut/Copy/Paste functions using Clipboard. Cut and Copy was very easy to implement, but I cannot make Paste routine. I do not want to copy and paste entire cell, but only copy selected text to Clipboard, and then paste it in another text cell in cursor position. How to achieve it?

Developer technologies Windows Forms
Developer technologies .NET Other
{count} vote

Accepted answer
  1. Reza Aghaei 4,986 Reputation points MVP Volunteer Moderator
    2022-07-22T11:35:43.017+00:00

    There's a built-in support for Copy and Paste in the DataGridViewTextBoxEditingControl (Well, it's basically a TextBox). So even if you don't code, the default [Ctrl]+[C], [Ctrl]+[X], and [Ctrl]+[V] will work just fine. You just need to enter edit mode of the cell, select a piece of text, press the [Ctrl]+[C], then go to another cell, enter edit mode, select something or click in middle of the text, press [Ctrl]+[V] and it works as expected.

    But if for some reason, you would like to have some ToolStipButton for copy/paste, you can just add a ToolStrip, having some buttons, handle click event like this:

    private void toolStripButtonCopy_Click(object sender, EventArgs e)  
    {  
        var txt = dataGridView1.EditingControl as TextBox;  
        if (txt != null)  
        {  
            txt.Copy();  
        }  
    }  
    
    private void toolStripButtonPaste_Click(object sender, EventArgs e)  
    {  
        var txt = dataGridView1.EditingControl as TextBox;  
        if (txt != null)  
        {  
            txt.Paste();  
        }  
    }  
    

    Please keep in mind, Button will not work in this case, because it steals the focus and the DataGridView.EditingControl will disappear.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.