C1Flexgrid for WinForms provides OLE Drag/Drop functionality using its DragMode and DropMode properties initiated by dragging of column headers from one grid to another. The OLE Drag and Drop mechanism provides several events which the application traps to implement drag and drop operations from the source to the target. This article explains an approach to move columns between two C1FlexGrid controls.
Enable Drag & Drop
First of all populate the two C1FlexGrid and set their DragMode and DropMode properties to Manual as shown below.
// both are OLE drag sources
_flexLeft.DragMode = DragModeEnum.Manual;
_flexRight.DragMode = DragModeEnum.Manual;
// both are OLE drop targets
_flexLeft.DropMode = DropModeEnum.Manual;
_flexRight.DropMode = DropModeEnum.Manual;
Handle Drag & Drop of Columns
To implement the drag/drop operations, you need to handle three events of C1FlexGrid controls.
-
BeforeMouseDown - To initiate DragDrop operation and check if mouse click is done on Column Header
-
DragOver - Handle dragging effects
-
DragDrop - Move Column from Source grid to Target grid
While moving the column from Source to the Target, you will need to verify that the Target object is a C1FlexGrid control.
private void \_flex\_BeforeMouseDown(object sender, C1.Win.C1FlexGrid.BeforeMouseDownEventArgs e)
{
// start dragging when the user clicks the column headers
C1FlexGrid flex = sender as C1FlexGrid;
HitTestInfo hti = flex.HitTest(e.X, e.Y);
if (hti.Type == HitTestTypeEnum.ColumnHeader)
{
// select the col
int indexCol = hti.Column;
flex.Select(0, indexCol, flex.Rows.Count - 1, indexCol, false);
// save info for target
_src = flex;
// do drag drop
DragDropEffects dd = flex.DoDragDrop(flex.Clip, DragDropEffects.Move);
// if it worked, delete column from source (it's a move)
if (dd == DragDropEffects.Move)
flex.Cols.Remove(indexCol);
// done, reset info
_src = null;
}
}
private void \_flex\_DragOver(object sender, System.Windows.Forms.DragEventArgs e)
{
// check whether we can drop here:
// we must have a source object, and it should be the
// other C1FlexGrid control.
if (\_src != null && !\_src.Equals(sender))
{
// check that we have the type of data we want
if (e.Data.GetDataPresent(typeof(string)))
e.Effect = DragDropEffects.Move;
}
}
private void \_flex\_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
C1FlexGrid flex = sender as C1FlexGrid;
Point pt = flex.PointToClient(new Point(e.X, e.Y));
HitTestInfo hti = flex.HitTest(pt.X, pt.Y);
int indexCol = hti.Column;
if (indexCol < 0) indexCol = flex.Cols.Count; // append
if (indexCol < 1) indexCol = 1; // after fixed column
// insert a new col at the drop position
flex.Cols.Insert(indexCol);
// copy data from source row
flex.Select(0, indexCol, flex.Rows.Count - 1, indexCol, false);// flex.Cols.Count-1, false);
flex.Clip = (string)e.Data.GetData(typeof(string));
}