Possible to allow copy-paste of multiple datagridview rows?

  • Thread starter Thread starter Earl
  • Start date Start date
E

Earl

I've never done this before, so I'm wondering if it's possible and if there
is a sample. Fundamentally, is it possible to do the same thing you might do
with an Access grid -- allow the user to highlight mutliple rows with
identical structure then copy and paste them into the datagridview? I can
somewhat visualize the code to do this but I'm hoping it is easier than what
I speculate. Is there a sample somewhere on how to do this?
 
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, dataGridView1[col + i, row].ValueType);
}
else
{
break;
}
}
row++;
}
else
{
break;
}
}
}
}

=================
Clay Burch
Syncfusion, Inc.
 
Thanks Clay, that looks very helpful. I will get back to that in a few days
and let you know how it works out.
 
Back
Top