Introduction
This is my first article and I going to explain how we can copy or move data from one datagrid view to another using Drag N Drop feature.
Background
AFTER reading lots of articles on various sites, I got to know that it's easy to add a row or column to DataGridView
control using dragdrop. But there is a problem when we have to add data to a single cell because during drag of data we are unable to get cells rowIndex
and ColumnIndex
. So we have to determine using the X and Y coordinates returned by the mouse pointer.
Using the Code
There are only three main events that you have to handle.
CellMouseDown
for the DataGridView
(dataGridView2
in my case) from which data is copied. We write the following code:
private void dataGridView2_CellMouseDown
(object sender, DataGridViewCellMouseEventArgs e)
{
dataGridView2.DoDragDrop(dataGridView2.Rows
[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(),
DragDropEffects.Copy);
}
DragEnter
event of the DataGridView
(dataGridView1
in my case) in which data is to be pasted.
private void dataGridView1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(System.String)))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
- Finally
DragDrop
event of the DataGridView
(dataGridView1
in my case) in which data is to be pasted.
private void dataGridView1_DragDrop(object sender, DragEventArgs e) {
if (e.Data.GetDataPresent(typeof(System.String)))
{
Point clientPoint = dataGridView1.PointToClient(new Point(e.X, e.Y));
dataGridView1.Rows[dataGridView1.HitTest(clientPoint.X,
clientPoint.Y).RowIndex].Cells[dataGridView1.HitTest(clientPoint.X,
clientPoint.Y).ColumnIndex].Value =
(System.String)e.Data.GetData(typeof(System.String));
}
}
Similarly, you can use drag and drop for other controls as well.
I hope it will help you.
Happy coding!!!!!!!!!!!!!
Best of luck.
History
- 18th February, 2010: Initial post