Just as its name states, C1FlexGrid is one of the most flexible controls in which almost everything can be performed. In this blog, we will be implementing the drag and drop functionality for the columns in two different grids. Yes, just pick up a column from one grid, drag it to the other grid and drop it. That's it! Lets have a look at the list of events of C1FlexGrid that would help follow through our requirement:
1. The BeforeMouseDown event would help in getting the column that is to be dragged.
private void \_flex\_BeforeMouseDown(object sender, C1.Win.C1FlexGrid.BeforeMouseDownEventArgs e)
{
// start dragging when the user clicks the row headers
C1FlexGrid flex = sender as C1FlexGrid;
HitTestInfo hti = flex.HitTest(e.X, e.Y);
if (hti.Type == HitTestTypeEnum.ColumnHeader)
{
// select the row
int index = hti.Column;
flex.Select(1, index, flex.Rows.Count-1, index, false);
// save info for target
_src = flex;
// do drag drop
DragDropEffects dd = flex.DoDragDrop(flex.Clip, DragDropEffects.Move);
// if it worked, delete row from source (it's a move)
if (dd == DragDropEffects.Move)
flex.Cols.Remove(index);
// done, reset info
_src = null;
}
}
2. Just after the BeforMouseDown event, the DragOver event needs to be handled. The aim to handle this event is to make sure that we have the correct data. This can be done by getting the data using the GetDataPresent method of IDataObject.
private void \_flex\_DragOver(object sender, System.Windows.Forms.DragEventArgs e)
{
if (\_src != null && !\_src.Equals(sender))
{
if (e.Data.GetDataPresent(typeof(string)))
e.Effect = DragDropEffects.Move;
}
}
3. The last step is to handle the DragDrop event which would help in getting the Column. In this event, the insertion of the new column on the second grid needs to be handled.
// insert a new row at the drop position
flex.Cols.Insert(index);
// copy data from source row
flex.Select(1, index, flex.Rows.Count - 1, index, false);
flex.Clip = (string)e.Data.GetData(typeof(string));
And there you have it, the functionality to drag and drop columns from one C1FlexGrid to the other :) Download C# Sample Download VB Sample