The attached samples (C#, VB) have a derived DataGrid that supports OLE D&D with any OLE D&D provider that handles a Text formatted data object. The derived grid handles six events to allow it to be both a drop source and a drop target. The sample project has two DataGrid where you can drag cell text back and forth. You can also open Excel, and drag text between Excel and either DataGrid.
Here are the events that are handled in this sample.
MouseDown - Used to save the row and column of a mousedown, 'mousedowncell'.
MouseMove - Checks to see if you drag off the mousedowncell, and if so, starts a the DoDragDrop.
MouseUp - Used to reset the mousedowncell.
DragEnter - Checks to see if the data object has text, and if so, allows a Copy operation. (This could be changed to support Move/Copy.)
DragOver - Used to set a NoDrop cursor if you move over the mousedowncell (if mousedowncell has been set).
DragDrop - Used to drop the text into the DataGrid.
One way to do this is to derive a DataGrid, override its OnMouseDown and OnMouseMove methods. In the OnMouseDown, handle selecting and unselecting in your code without calling the base class if the click is on the header. In the OnMouseMove, don't call the base class to avoid dragging selections. Below is a code snippet for a sample derived DataGrid. You can download a full project (C#, VB).
public class CustomDataGrid : DataGrid
{
private int oldSelectedRow = -1;
protected override void OnMouseMove( MouseEventArgs e )
{
//don't call the base class if left mouse down
if ( e.Button != MouseButtons.Left )
base.OnMouseMove( e );
}
protected override void OnMouseDown( MouseEventArgs e )
{
//don't call the base class if in header
DataGrid.HitTestInfo hti = HitTest( new Point( e.X, e.Y ) );
if ( hti.Type == DataGrid.HitTestType.Cell )
{
if ( oldSelectedRow > -1 )
UnSelect( oldSelectedRow );
oldSelectedRow = -1;
base.OnMouseDown( e );
}
else if ( hti.Type == DataGrid.HitTestType.RowHeader )
{
if ( oldSelectedRow > -1 )
UnSelect( oldSelectedRow );
if ( (Control.ModifierKeys & Keys.Shift) == 0 )
base.OnMouseDown( e );
else
CurrentCell = new DataGridCell( hti.Row, hti.Column );
Select( hti.Row );
oldSelectedRow = hti.Row;
}
}
}
Contributed from George Shepherd's Windows Forms FAQ