DataGridView 控件复制粘贴功能
复制,直接用剪切板
1 if (dgvData.GetCellCount(DataGridViewElementStates.Selected) > 0) 2 { 3 Clipboard.SetDataObject(dgvData.GetClipboardContent(), false); 5 }
粘贴功能
DataObject o = (DataObject)Clipboard.GetDataObject(); if (o.GetDataPresent(DataFormats.Text)) { int rowOfInterest = dgvData.CurrentCell.RowIndex; string[] selectedRows = Regex.Split(o.GetData(DataFormats.Text).ToString().TrimEnd("\r\n".ToCharArray()), "\r\n"); if (selectedRows == null || selectedRows.Length == 0) return; foreach (string row in selectedRows) { if (rowOfInterest >= dgvData.Rows.Count) break; try { string[] data = Regex.Split(row, "\t"); int col = dgvData.CurrentCell.ColumnIndex; foreach (string ob in data) { if (col >= dgvData.Columns.Count) break; if (ob != null) dgvData[col, rowOfInterest].Value = Convert.ChangeType(ob, dgvData[col, rowOfInterest].ValueType); col++; } } catch (Exception enterException) { } rowOfInterest++; } }