Click here to Skip to main content
15,888,020 members
Articles / Programming Languages / C#
Tip/Trick

Copy Paste in Datagridview Control

Rate me:
Please Sign up or sign in to vote.
4.71/5 (13 votes)
8 Jun 2011CPOL 120.5K   5.8K   23   13
How to copy paste in Datagridview control

Introduction

This post discusses how to add a datagridview and a contextmenustrip with cut, copy and paste into the form.

Image 1

Populate the DataGridView and define the click events as follows:

C#
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    if (dataGridView1.SelectedCells.Count > 0)
        dataGridView1.ContextMenuStrip = contextMenuStrip1;
}

private void cutToolStripMenuItem_Click(object sender, EventArgs e)
{
    //Copy to clipboard
    CopyToClipboard();

    //Clear selected cells
    foreach (DataGridViewCell dgvCell in dataGridView1.SelectedCells)
        dgvCell.Value = string.Empty;
}

private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
    CopyToClipboard();
}

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
    //Perform paste Operation
    PasteClipboardValue();
}

Copy/Paste routines follow...

The clipboard values are saved in a Dictionary, so the user can validate or manipulate the values before assigning them into gridviewcell.

C#
private void CopyToClipboard()
{
    //Copy to clipboard
    DataObject dataObj = dataGridView1.GetClipboardContent();
    if (dataObj != null)
        Clipboard.SetDataObject(dataObj);
}

private void PasteClipboardValue()
{
    //Show Error if no cell is selected
    if (dataGridView1.SelectedCells.Count == 0)
    {
        MessageBox.Show("Please select a cell", "Paste", 
		MessageBoxButtons.OK, MessageBoxIcon.Warning);
        return;
    }

    //Get the starting Cell
    DataGridViewCell startCell = GetStartCell(dataGridView1);
    //Get the clipboard value in a dictionary
    Dictionary<int, Dictionary<int, string>> cbValue = 
			ClipBoardValues(Clipboard.GetText());

    int iRowIndex = startCell.RowIndex;
    foreach (int rowKey in cbValue.Keys)
    {
        int iColIndex = startCell.ColumnIndex;
        foreach (int cellKey in cbValue[rowKey].Keys)
        {
            //Check if the index is within the limit
            if (iColIndex <= dataGridView1.Columns.Count - 1
            && iRowIndex <= dataGridView1.Rows.Count - 1)
            {
                DataGridViewCell cell = dataGridView1[iColIndex, iRowIndex];

                //Copy to selected cells if 'chkPasteToSelectedCells' is checked
                if ((chkPasteToSelectedCells.Checked && cell.Selected) ||
                    (!chkPasteToSelectedCells.Checked))
                    cell.Value = cbValue[rowKey][cellKey];
            }
            iColIndex++;
        }
        iRowIndex++;
    }
}

private DataGridViewCell GetStartCell(DataGridView dgView)
{
    //get the smallest row,column index
    if (dgView.SelectedCells.Count == 0)
        return null;

    int rowIndex = dgView.Rows.Count - 1;
    int colIndex = dgView.Columns.Count - 1;

    foreach (DataGridViewCell dgvCell in dgView.SelectedCells)
    {
        if (dgvCell.RowIndex < rowIndex)
            rowIndex = dgvCell.RowIndex;
        if (dgvCell.ColumnIndex < colIndex)
            colIndex = dgvCell.ColumnIndex;
    }

    return dgView[colIndex, rowIndex];
}

private Dictionary<int, Dictionary<int, string>> ClipBoardValues(string clipboardValue)
{
    Dictionary<int, Dictionary<int, string>>
    copyValues = new Dictionary<int, Dictionary<int, string>>();

    String[] lines = clipboardValue.Split('\n');

    for (int i = 0; i <= lines.Length - 1; i++)
    {
        copyValues[i] = new Dictionary<int, string>();
        String[] lineContent = lines[i].Split('\t');

        //if an empty cell value copied, then set the dictionary with an empty string
        //else Set value to dictionary
        if (lineContent.Length == 0)
            copyValues[i][0] = string.Empty;
        else
        {
            for (int j = 0; j <= lineContent.Length - 1; j++)
                copyValues[i][j] = lineContent[j];
        }
    }
    return copyValues;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer UVJ Technologies
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionimage also can be pasted?? Pin
Member 1453394522-Mar-21 23:18
Member 1453394522-Mar-21 23:18 
PraiseGood work Pin
Member 1268962927-Aug-19 3:51
Member 1268962927-Aug-19 3:51 
QuestionchkPasteToSelectedCells Pin
n shiva Ram24-Sep-14 2:02
n shiva Ram24-Sep-14 2:02 
QuestionExcellent thanks. Used this with derived DataGridView class. Pin
Member 1062780723-Jul-14 5:02
Member 1062780723-Jul-14 5:02 
QuestionIs it possible to Force Single Cell Only Pin
Member 171591218-Feb-14 1:32
Member 171591218-Feb-14 1:32 
GeneralThanks Pin
Mikles, Max Mikles29-Apr-13 14:45
Mikles, Max Mikles29-Apr-13 14:45 
Questionconvert to vb.net Pin
mr.fugio29-Nov-12 19:57
mr.fugio29-Nov-12 19:57 
AnswerRe: convert to vb.net Pin
Michael Paschal25-Mar-15 14:25
Michael Paschal25-Mar-15 14:25 
Here it is in vb.net:

VB


Private Sub dgvReturnSeries_CellMouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles dgvReturnSeries.CellMouseClick
'if the datagridview was right clicked, set the currentcell to the right-clicked cell and then show a context menu with options for filling the right-clicked cell
If (e.Button = Windows.Forms.MouseButtons.Right) Then
Try
'highlight the right-clicked cell, make it the dgv's current cell
dgvReturnSeries.CurrentRow.Selected = False
dgvReturnSeries.Rows(e.RowIndex).Selected = True
dgvReturnSeries.CurrentCell = dgvReturnSeries.Rows(e.RowIndex).Cells(e.ColumnIndex)
dgvReturnSeries.ContextMenuStrip = ContextMenuStrip1
Catch ex As Exception
MsgBox(ex.Message)
End Try

End If
End Sub
'Private Sub dgvReturnSeries_CellMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs)
' If (dgvReturnSeries.SelectedCells.Count > 0) Then
' dgvReturnSeries.ContextMenuStrip = ContextMenuStrip1
' End If
'End Sub
Private Sub cutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CutToolStripMenuItem.Click
' Copy to clipboard
CopyToClipboard()
' Clear selected cells
For Each dgvCell As DataGridViewCell In dgvReturnSeries.SelectedCells
dgvCell.Value = String.Empty
Next
End Sub
Private Sub copyToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CopyToolStripMenuItem.Click
CopyToClipboard()
End Sub
Private Sub pasteToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles PasteToolStripMenuItem.Click
' Perform paste Operation
PasteClipboardValue()
End Sub
Private Sub CopyToClipboard()
' Copy to clipboard
Dim dataObj As DataObject = dgvReturnSeries.GetClipboardContent()
If (Not IsNothing(dataObj)) Then
Clipboard.SetDataObject(dataObj)
End If
End Sub
Private Sub PasteClipboardValue()
' Show Error if no cell is selected
If (dgvReturnSeries.SelectedCells.Count = 0) Then
MessageBox.Show("Please select a cell", "Paste", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If

' Get the starting Cell
Dim startCell As DataGridViewCell = GetStartCell(dgvReturnSeries)
' Get the clipboard value in a dictionary
Dim cbValue As New Dictionary(Of Integer, Dictionary(Of Integer, String))
cbValue = ClipBoardValues(Clipboard.GetText())

Dim iRowIndex As Integer = startCell.RowIndex
For Each rowKey As Integer In cbValue.Keys
Dim iColIndex As Integer = startCell.ColumnIndex
For Each cellKey As Integer In cbValue(rowKey).Keys
' Check if the index is within the limit
If (iColIndex <= dgvReturnSeries.Columns.Count - 1 And _
iRowIndex <= dgvReturnSeries.Rows.Count - 1) Then
Dim cell As DataGridViewCell = dgvReturnSeries(iColIndex, iRowIndex)
cell.Value = cbValue(rowKey)(cellKey)
End If
iColIndex += 1
Next
iRowIndex += 1
Next
End Sub
Private Function GetStartCell(dgView As DataGridView) As DataGridViewCell
' get the smallest row,column index
If (dgView.SelectedCells.Count = 0) Then
Return Nothing
End If
Dim rowIndex As Integer = dgView.Rows.Count - 1
Dim colIndex As Integer = dgView.Columns.Count - 1

For Each dgvCell As DataGridViewCell In dgView.SelectedCells
If (dgvCell.RowIndex < rowIndex) Then
rowIndex = dgvCell.RowIndex
End If
If (dgvCell.ColumnIndex < colIndex) Then
colIndex = dgvCell.ColumnIndex
End If
Next
Return dgView(colIndex, rowIndex)
End Function
Private Function ClipBoardValues(clipboardValue As String) As Dictionary(Of Integer, Dictionary(Of Integer, String))
Dim copyValues As Dictionary(Of Integer, Dictionary(Of Integer, String)) = _
New Dictionary(Of Integer, Dictionary(Of Integer, String))()

Dim lines As String() = clipboardValue.Split(vbCrLf)

For i As Integer = 0 To lines.Length - 1
copyValues(i) = New Dictionary(Of Integer, String)()
Dim lineContent As String() = lines(i).Split("\t")

' if an empty cell value copied, then set the dictionary with an empty string
' else Set value to dictionary
If (lineContent.Length = 0) Then
copyValues(i)(0) = String.Empty
Else
For j As Integer = 0 To lineContent.Length - 1
copyValues(i)(j) = lineContent(j)
Next
End If
Next
Return copyValues
End Function
Question...? Pin
Member 92618739-Aug-12 23:49
Member 92618739-Aug-12 23:49 
AnswerRe: ...? Pin
rndtech15-Jul-13 13:20
professionalrndtech15-Jul-13 13:20 
GeneralGreat Code Pin
HolyHannah21-Jun-12 3:27
HolyHannah21-Jun-12 3:27 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey5-Apr-12 7:53
professionalManoj Kumar Choubey5-Apr-12 7:53 
QuestionCopy and Paste Pin
Anthony Fonseca5-Jul-11 16:20
Anthony Fonseca5-Jul-11 16:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.