Skip to main content Skip to footer

Add Drag & Drop functionality in C1TrueDBGrid

Background:

How to achieve Drag & Drop functionality in TrueDBGrid

Steps to Complete:

1. Set the AllowDrag and AllowDrop properties to true in order to enable drag and drop rows within the grid.

C1TrueDBGrid1.AllowDrag = True
C1TrueDBGrid1.AllowDrop = True

2. Handle the following Mouse and Drag/Drop events.

Dim dragBoxFromMouseDown As Rectangle = Nothing
Dim rowIndexFromMouseDown As Integer = 0
Dim rowIndexOfItemUnderMouseToDrop As Integer = 0

//Get the Rectangle of the Selected Row to be Dragged
Private Sub C1TrueDBGrid1_MouseDown(sender As Object, e As MouseEventArgs) Handles C1TrueDBGrid1.MouseDown
rowIndexFromMouseDown = C1TrueDBGrid1.RowContaining(e.Y)
If rowIndexFromMouseDown <> -1 Then
Dim dragSize As Size = SystemInformation.DragSize
dragBoxFromMouseDown = New Rectangle(New Point(e.X - (dragSize.Width / 2), e.Y - (dragSize.Height / 2)), dragSize)
  Else
    dragBoxFromMouseDown = Rectangle.Empty
End If
End Sub

//Move the Selected Row To Another Index using DODragDrop method
Private Sub C1TrueDBGrid1_MouseMove(sender As Object, e As MouseEventArgs) Handles C1TrueDBGrid1.MouseMove
If (e.Button And MouseButtons.Left) = MouseButtons.Left Then
If dragBoxFromMouseDown <> Rectangle.Empty AndAlso Not dragBoxFromMouseDown.Contains(e.X, e.Y) Then
Dim dropEffect As DragDropEffects = C1TrueDBGrid1.DoDragDrop(C1TrueDBGrid1.Splits(0).Rows(rowIndexFromMouseDown), DragDropEffects.Move)
End If
End If
End Sub

//Define the drag effect in DragOver event 
 Private Sub C1TrueDBGrid1_DragOver(sender As Object, e As DragEventArgs) Handles C1TrueDBGrid1.DragOver
e.Effect = DragDropEffects.Move
End Sub

//After DragDrop operation update the DataSource of TDB accordingly
Private Sub C1TrueDBGrid1_DragDrop(sender As Object, e As DragEventArgs) Handles
C1TrueDBGrid1.DragDrop
 Dim clientPoint As Point = C1TrueDBGrid1.PointToClient(New Point(e.X, e.Y))
rowIndexOfItemUnderMouseToDrop = C1TrueDBGrid1.RowContaining(clientPoint.Y)
If C1TrueDBGrid1.PointAt(clientPoint.X, clientPoint.Y) = C1.Win.C1TrueDBGrid.PointAtEnum.AtDataArea Then
          If e.Effect = DragDropEffects.Move Then
                Dim rowToMove As DataRow = dt.NewRow()
                 rowToMove.ItemArray = dt.Rows(rowIndexFromMouseDown).ItemArray 
                dt.Rows.RemoveAt(rowIndexFromMouseDown)
             dt.Rows.InsertAt(rowToMove, rowIndexOfItemUnderMouseToDrop)
            End If C1TrueDBGrid1.DataSource = dt
 End If
 End Sub

Prabhat Sharma