I am trying to copy the value of a celda
or several and to paste it to another (%) celda(s)
. I currently have this basic method that works.
myDataGrid.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText;
Datagridview KeyDown event:
if (e.Control && e.KeyCode == Keys.C)
{
DataObject objeto_datos = myDataGrid.GetClipboardContent();
Clipboard.SetDataObject(objeto_datos);
e.Handled = true;
}
else
if (e.Control && e.KeyCode == Keys.V)
{
string texto_obtenido = Clipboard.GetText();
string[] lineas = texto_obtenido.Split('\n');
int fila = myDataGrid.CurrentCell.RowIndex;
int columna = myDataGrid.CurrentCell.ColumnIndex;
string[] celdas = lineas[0].Split('\t');
int celdas_seleccionadas = celdas.Length;
for (int indice = 0; indice < celdas_seleccionadas; indice++)
{
dgrid_hoja_horas[columna, fila].Value = celdas[indice];
columna++;
}
}
Being a very basic method, certain controls and validations are missing:
- I need to avoid pasting data into cells
ReadOnly
. -
The
celda
should only accept the pasting of data, if the copied data matches the value format of the cell . Formats: (Datetime
,Decimal
,String
...). (Otherwise show some exception). - I use this method in different forms so it would be easier to create a function and not have to duplicate the code .
Note: I know that this topic can be considered broad, but I would accept any solution that you can offer me.
I use: Visual Studio 2010 and .NET Netframework 4
Edited:
Download Sample Code: CopyPegarDatagridview.zip Google Drive Link, Inside there is a TXT file read it please.