Here is some code that will allow you to copy/paste text, say from
Excel to a DataGridView or a DataGridView to a DataGridView. It uses
the KeyDown event to catch the ctl+V and ctl+C.
this.dataGridView1.KeyDown += new
KeyEventHandler(dataGridView1_KeyDown);
void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.C)
{
DataObject d = dataGridView1.GetClipboardContent();
Clipboard.SetDataObject(d);
e.Handled = true;
}
else if(e.Control && e.KeyCode == Keys.V)
{
string s = Clipboard.GetText();
string[] lines = s.Split('/n');
int row = dataGridView1.CurrentCell.RowIndex;
int col = dataGridView1.CurrentCell.ColumnIndex;
foreach (string line in lines)
{
if (row < dataGridView1.RowCount && line.Length >
0)
{
string[] cells = line.Split('/t');
for (int i = 0; i < cells.GetLength(0); ++i)
{
if (col + i <
this.dataGridView1.ColumnCount)
{
dataGridView1[col + i, row].Value =
Convert.ChangeType(cells[i], dataGridView1[col + i, row].ValueType);
}
else
{
break;
}
}
row++;
}
else
{
break;
}
}
}
}
資料來源:
http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework.adonet/topic62493.aspx