Search code examples
c#winformsdatagridviewtextboxcell

Ctrl + c in DataGridViewCell edit mode copies the whole row


I have a datagrid that has one column with text that I would like to allow users to copy text out of. I have set up routines to be able to copy the entire cell, or row, but I am having issues when editing the cell and typing CTRL + C.

This is the code I am using to allow the cell to be edited. Once inside, I can highlight text and right click it for copy. This works just fine, it is if I highlight text and type CTRL + C that it then copies the row, instead of the highlighted text.

I don't want to have to create my own class, and if it isn't possible I will just leave it as it is.

private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
{
    if (dataGridView1.EditingControl == null ||
    dataGridView1.CurrentCell.EditType != typeof (DataGridViewTextBoxEditingControl))
    return;
    dataGridView1.CancelEdit();
    dataGridView1.EndEdit();
}

private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
    if (dataGridView1.CurrentCell.EditType == typeof(DataGridViewTextBoxEditingControl))
    {
    dataGridView1.BeginEdit(false);
    }
}

Solution

  • If you are having the SelectionMode property as FullRowSelect then it will copy the entire row even if a cell is in edit mode. Change the value to CellSelect. Set the below properties to copy only the editing cell content using CTRL + C.

    dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;
    dataGridView1.MultiSelect = false;