单列DGV接受剪贴板数据

时间:2012-05-17 10:52:46

标签: c# .net winforms datagridview

我已经设置了一个windowsform。 目前它有一个DataGridView链接到SQL Server数据库中的单个表。 我可以浏览表格中的当前数据。

如何进行设置,以便用户可以将Excel表格中的单列数据复制并粘贴到DGV中?

如果在Excel中我在A1中有'x'而在A2中有'y'那么这必须保留粘贴到DGV时的行数,即对于这个例子,它仍然会超过2行

我试图从Code Project改编以下内容。如果(oCell.Value.ToString() != sCells[i])带有NullReferenceException was unhandled private void uxChargeBackDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { PasteClipboard(); //uxChargeBackDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = Clipboard.GetText(); } private void PasteClipboard() { try { string s = Clipboard.GetText(); string[] lines = s.Split('\n'); int iFail = 0, iRow = uxChargeBackDataGridView.CurrentCell.RowIndex; int iCol = uxChargeBackDataGridView.CurrentCell.ColumnIndex; DataGridViewCell oCell; foreach (string line in lines) { if (iRow < uxChargeBackDataGridView.RowCount && line.Length > 0) { string[] sCells = line.Split('\t'); for (int i = 0; i < sCells.GetLength(0); ++i) { if (iCol + i < this.uxChargeBackDataGridView.ColumnCount) { oCell = uxChargeBackDataGridView[iCol + i, iRow]; if (!oCell.ReadOnly) { if (oCell.Value.ToString() != sCells[i]) { oCell.Value = Convert.ChangeType(sCells[i], oCell.ValueType); oCell.Style.BackColor = Color.Tomato; } else iFail++; //only traps a fail if the data has changed //and you are pasting into a read only cell } } else { break; } } iRow++; } else { break; } if (iFail > 0) MessageBox.Show(string.Format("{0} updates failed due" + " to read only column setting", iFail)); } } catch (FormatException) { MessageBox.Show("The data you pasted is in the wrong format for the cell"); return; } } 我做错了怎么办?

{{1}}

2 个答案:

答案 0 :(得分:1)

非常简单并且可以解决问题:

private void gridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e) 
{
    gridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = Clipboard.GetText();
}

编辑*

如果要粘贴到多个单元格而不是单个单元格,请查看此博客文章:

http://happysoftware.blogspot.co.uk/2011/07/c-code-snippet-paste-to-datagridview.html

答案 1 :(得分:0)

参考这些:how to PASTE (Ctrl+V, Shift+Ins) the data from clipboard to DataGridView (DataGridView1) C#Copy and paste into a DataGridView cell (C#)

private void 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))
    {
       /// your paste copy/paste code here
    }
}

有很多参考SO Thread和关于这个主题的另一篇文章遵循这些来实现你的任务.. DataGridView Copy and Paste
Copy Paste in Datagridview Control
DataGridView DataBound Copy, Paste, Drag, Drop
Row copy/paste functionality in DataGridview(windows application)

Get cell contents of a selected row in a DataGridView
How to: Get the Selected Cells, Rows, and Columns in the Windows Forms DataGridView Control

希望这有帮助..