C#

How to drag information from a DataGridView control

Let’s see how we can drag information from a DataGridView control in C#.
We need to handle two events, MouseMove and MouseDown.

private Rectangle dragbox;
private int DragSelectedRow;
 
private void dgvc_MouseMove(object sender, MouseEventArgs e)
{
	if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
	{
		if (dragbox != Rectangle.Empty &&
			!dragbox.Contains(e.X, e.Y))
		{                 
			DragDropEffects dropEffect = dgvc.DoDragDrop(
				dgvc.Rows[DragSelectedRow],
				DragDropEffects.Move);
		}
	}
 
}
 
private void dgvc_MouseDown(object sender, MouseEventArgs e)
{
	DragSelectedRow = dgvc.HitTest(e.X, e.Y).RowIndex;
	if (DragSelectedRow != -1)
	{            
		Size dragSize = SystemInformation.DragSize;
		dragbox = new Rectangle(new Point(e.X - (dragSize.Width / 2), 
                   e.Y - (dragSize.Height / 2)), dragSize);
	}
	else
		dragbox = Rectangle.Empty;
}