Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy datagridview cell content to clipboard in FullRowSelect Mode

I have a winform datagridview to show customer details and it has a context menu. And I have set the datagridview selection Mode to "FullRowSelect". What i want is i want to copy the content of the clicked cell content to the clipboard. Not the whole row content. Just the cell content.

I have used the following code to show the Context Menu when it right click on the datagridview and select the row.

private void dgvCusList_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
    {
        if (e.RowIndex != -1 && e.ColumnIndex != -1)
        {
            if (e.Button == MouseButtons.Right)
            {
                DataGridViewCell clickedCell = (sender as DataGridView).Rows[e.RowIndex].Cells[e.ColumnIndex];

                this.dgvCusList.CurrentCell = clickedCell;  

                var relativeMousePosition = dgvCusList.PointToClient(Cursor.Position);

                this.cnxtMnuCusResult.Show(dgvCusList, relativeMousePosition);
            }
        }
    } 

I want to copy the the cell content to clipboard when i click copy menu item in my context menu. Please help me to solove this matter. Thanks in advance. :)

like image 315
Daybreaker Avatar asked Dec 07 '22 03:12

Daybreaker


2 Answers

If you are having the SelectionMode property as FullRowSelect then copy functionality of DataGridView will copy the entire row. Change the value to CellSelect. Set the below properties to copy only the cell content.

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

If you want to retain the FullRowSelect selection mode, then do like below..

 void contextMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
    {
        if (e.ClickedItem.Text == "Copy" && dataGridView1.CurrentCell.Value != null)
        {
            Clipboard.SetDataObject(dataGridView1.CurrentCell.Value.ToString(), false);
        }
    }

 void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right && e.ColumnIndex != -1 && e.RowIndex != -1)
        {
            dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ContextMenuStrip = contextMenu;
            dataGridView1.CurrentCell = myDGV.Rows[e.RowIndex].Cells[e.ColumnIndex];
        }
    }
like image 181
Junaith Avatar answered Dec 10 '22 13:12

Junaith


In contextMenu or CellDoubleClick Event or cellMouseClick event , you can do the following

Clipboard.SetText(dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString());

It will copy the particular cell's Content

like image 34
yasmuru Avatar answered Dec 10 '22 11:12

yasmuru