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:
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (dataGridView1.SelectedCells.Count > 0)
dataGridView1.ContextMenuStrip = contextMenuStrip1;
}
private void cutToolStripMenuItem_Click(object sender, EventArgs e)
{
CopyToClipboard();
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)
{
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
.
private void CopyToClipboard()
{
DataObject dataObj = dataGridView1.GetClipboardContent();
if (dataObj != null)
Clipboard.SetDataObject(dataObj);
}
private void PasteClipboardValue()
{
if (dataGridView1.SelectedCells.Count == 0)
{
MessageBox.Show("Please select a cell", "Paste",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
DataGridViewCell startCell = GetStartCell(dataGridView1);
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)
{
if (iColIndex <= dataGridView1.Columns.Count - 1
&& iRowIndex <= dataGridView1.Rows.Count - 1)
{
DataGridViewCell cell = dataGridView1[iColIndex, iRowIndex];
if ((chkPasteToSelectedCells.Checked && cell.Selected) ||
(!chkPasteToSelectedCells.Checked))
cell.Value = cbValue[rowKey][cellKey];
}
iColIndex++;
}
iRowIndex++;
}
}
private DataGridViewCell GetStartCell(DataGridView dgView)
{
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 (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;
}