//可在dgv中复制、剪切、粘贴、删除数据 /// <summary> /// DataGridView复制 /// </summary> /// <param name="dgv">DataGridView实例</param> public static void dgvCopy(DataGridView dgv) { if (dgv.GetCellCount(DataGridViewElementStates.Selected) > 0) { try { Clipboard.SetDataObject(dgv.GetClipboardContent()); } catch (Exception MyEx) { MessageBox.Show(MyEx.Message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } /// <summary> /// DataGridView剪切 /// </summary> /// <param name="dgv">DataGridView实例</param> public static void dgvCut(DataGridView dgv) { dgvCopy(dgv); try { dgvDel(dgv); } catch (Exception MyEx) { MessageBox.Show(MyEx.Message); } } ///<summary> /// DataGridView删除内容 /// </summary> /// <param name="dgv">DataGridView实例</param> public static void dgvDel(DataGridView dgv) { try { int k = dgv.SelectedCells.Count; for (int i = 0; i < k; i++) { dgv.SelectedCells[i].Value = ""; } } catch (Exception MyEx) { MessageBox.Show(MyEx.Message); } } /// <summary> /// DataGridView粘贴 /// </summary> /// <param name="dt">DataGridView数据源</param> /// <param name="dgv">DataGridView实例</param> public static void dgvPaste(DataGridView dgv) { try { //最后一行为新行 int rowCount = dgv.Rows.Count - 1; int colCount = dgv.ColumnCount; //获取剪贴板内容 string pasteText = Clipboard.GetText(); //判断是否有字符存在 if (string.IsNullOrEmpty(pasteText)) return; //以换行符分割的数组 string[] lines = pasteText.Trim().Split(' '); int txtLength = lines.Length; //Lance.2015-12-03 int cRowIndex = dgv.SelectedCells[0].RowIndex; int cColIndex = dgv.SelectedCells[0].ColumnIndex; for (int i = 0; i < txtLength; i++) { string[] words = lines[i].Split(' '); for (int j = 0; j < words.Length; j++) { dgv.Rows[cRowIndex + i].Cells[cColIndex + j].Value = words[j]; } } } catch (Exception MyEx) { MessageBox.Show(MyEx.Message); } }
Keys key = e.KeyCode; //Delete删除内容 if (key == Keys.Delete) { TextDaseOperationClass.dgvDel(dataGridView1); } if (e.Control!=true)//如果没按Ctrl键 return; switch (key) { case Keys.C: //按下Ctrl+C复制 TextDaseOperationClass.dgvCopy(dataGridView1); break; case Keys.V: //按下Ctrl+V粘贴 TextDaseOperationClass.dgvPaste(dataGridView1); break; case Keys.X: //按下Ctrl+V剪切 TextDaseOperationClass.dgvCut(dataGridView1); break; }