Hi there,
I was googling how to paste to DataGridView in C# from clipboard, an info, copied from Excel, and didn't find full answer.
Collected couple of threads from forums and came up with this answer,
hope it will make someones life easier.
You dont have to understand the code just copy and paste
//for example you have a form name=form1and datagridview name=grid
//what you have to do?
//change the property of your form "keypreview=true"
//double click on the KeyUp method of your form and copy paste the code below
//thats it, you dont have to do anything with datagridview except changing its name=grid in the property window
//_______________________________________________________________________________________________________________
privatevoid form1_KeyUp(object sender, KeyEventArgs e){
//if user clicked Shift+Ins or Ctrl+V (paste from clipboard)
if ((e.Shift && e.KeyCode == Keys.Insert) || (e.Control && e.KeyCode == Keys.V))
{
char[] rowSplitter = { '\r', '\n' };
char[] columnSplitter = { '\t' };
//get the text from clipboard
IDataObject dataInClipboard = Clipboard.GetDataObject();
string stringInClipboard = (string)dataInClipboard.GetData(DataFormats.Text);
//split it into lines
string[] rowsInClipboard = stringInClipboard.Split(rowSplitter, StringSplitOptions.RemoveEmptyEntries);
//get the row and column of selected cell in grid
int r = grid.SelectedCells[0].RowIndex;
int c = grid.SelectedCells[0].ColumnIndex;
//add rows into grid to fit clipboard lines
if (grid.Rows.Count < (r + rowsInClipboard.Length))
{
grid.Rows.Add(r + rowsInClipboard.Length - grid.Rows.Count);
}
// loop through the lines, split them into cells and place the values in the corresponding cell.
for (int iRow = 0; iRow < rowsInClipboard.Length; iRow++){
string[] valuesInRow = rowsInClipboard[iRow].Split(columnSplitter);//split row into cell values
//cycle through cell values
for (int iCol = 0; iCol < valuesInRow.Length; iCol++)
{
//assign cell value, only if it within columns of the grid
if (grid.ColumnCount-1 >= c + iCol)
{
grid.Rows[r + iRow].Cells[c + iCol].Value = valuesInRow[iCol];
}
}
}
}
}
//_______________________________________________________________________________________________________________
Any comments and improvements, welcome.
Thanks
Dil