DataGridView 区域 复制 粘贴 恢复 同Excel
选择区域Ctrl+C复制
找到要粘贴的位置Ctrl+V粘贴
发现粘贴错误Ctrl+Z恢复
注:目前只支持恢复一次
代码
private string[,] strHistory;
private int iRowHis, iColHis, iRowHisCount, iColHisCount;
private bool flag = false;
private void Form1_Load(object sender, EventArgs e)
{
int iRow = 10, iCol = 6;
Grid1.RowCount = iRow;
Grid1.ColumnCount = iCol;
for (int i = 0; i < iRow; i++)
for (int j = 0; j < iCol; j++)
Grid1.Rows[i].Cells[j].Value = i.ToString() + ":" + j.ToString();
}
private void FeiFu()
{
if (iRowHis == -1 || iColHis == -1) { return; }
for (int i = iRowHis; i < iRowHis +iRowHisCount; i++)
for (int j = iColHis; j < iColHis + iColHisCount; j++)
{
Grid1.Rows[i].Cells[j].Value = strHistory[i - iRowHis, j - iColHis];
}
}
private string GetCell(DataGridView grid, int ir, int ic)
{
try
{
return grid.Rows[ir].Cells[ic].Value.ToString();
}
catch
{
return "";
}
}
private void ZhanTie()
{
int iRow, iCol;
string line = string.Empty;
if (Grid1.CurrentCell == null) { return; }
iRow = Grid1.CurrentCell.RowIndex;
iCol = Grid1.CurrentCell.ColumnIndex;
if (iRow == -1 || iCol == -1) { return; }
iRowHis = iRow;
iColHis = iCol;
//这里是取剪贴板里的内容,如果内容为空,则退出
string pastTest = Clipboard.GetText();
if (string.IsNullOrEmpty(pastTest)) return;
//excel中是以 空格 和换行来 当做字段和行,所以用\n \r来分隔
string[] lines = pastTest.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
strHistory = new string[Grid1.RowCount - iRow, Grid1.ColumnCount - iCol];
for (int i = iRow; i < iRow + lines.Length; i++)
{
iRowHisCount = lines.Length;
line = lines[i - iRow];
string[] strs = line.Split(new char[] { '\t' });
if (i < Grid1.RowCount)
{
for (int j = iCol; j < iCol + strs.Length; j++)
{
iColHisCount = strs.Length;
if (j < Grid1.ColumnCount)
{
strHistory[i - iRow, j - iCol] = GetCell(Grid1, i, j);
Grid1.Rows[i].Cells[j].Value = strs[j - iCol];
Grid1.Rows[i].Cells[j].Selected = true;
flag = true;
}
}
}
}
}
private void Grid1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyValue == (char)Keys.V)
{
ZhanTie();
}
if (e.Control && e.KeyValue == (char)Keys.Z)
{
if (flag == true)
{
FeiFu();
flag = false;
}
}
}