TAdvStringGrid

Example 85 : VCL Drag & drop between TAdvStringGrid and a TTreeview

vcl grid drag and drop

This sample shows how simple VCL drag & drop can be used to drag cells from a grid to a treeview. It is important to notice that the grid's OLE drag & drop capabilities cannot be used here as the standard VCL treeview doesn't support OLE drag & drop. OLE drag & drop is supported by applications such as Explorer, Excel, Word,... In this sample, when the drop happens on an empty area of the treeview or a node with level 0, a new child node is inserted. When the drop happens on a node with level 1, the text of the node is updated with the cell text. Drag & drop starts from a drag from the grid and this is done by implementing the grid's OnMouseDown event:
procedure TForm2.AdvStringGrid1MouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  if Button = mbLeft then
  begin
    AdvStringGrid1.BeginDrag(false,5);
  end;
end;
The treeview implements both the OnDragOver and OnDragDrop event. The OnDragOver will make sure the mouse cursor is updated to a cursor indicating the drop will be accepted. In addition, when the mouse is over a collapsed node, the treeview will automatically expand the node:
procedure TForm2.TreeView1DragOver(Sender, Source: TObject; X, Y: Integer;
  State: TDragState; var Accept: Boolean);
var
  node:TTreeNode;
begin
  Accept := Source is TAdvStringGrid;
  if Accept then
  begin
    Node := TreeView1.GetNodeAt(x,y);
    if Node = nil then
      Exit;
    if Node.Level = 0 then
      Node.Expand(True);
  end;
end;
In the OnDragDrop event of the treeview, the actual drop is performed. Either a new node is inserted or the node text is updated:
procedure TForm2.TreeView1DragDrop(Sender, Source: TObject; X, Y: Integer);
var
  node:TTreeNode;
begin
  node := treeView1.GetNodeAt(x,y);

  if Assigned(Node) then
  begin
    if Node.Level = 0 then
      treeview1.Items.AddChild(node,(source as TAdvStringGrid).selectedText)
    else
      Node.Text := (source as TAdvStringGrid).selectedText;
  end
  else
    treeview1.Items.AddChild(node,(source as TAdvStringGrid).selectedText);
end;
This shows how easy it is to perform regular VCL drag & drop. The technique shown can be applied with any standard VCL component supporting drag & drop.

Delphi project & source files for downloading included in the main demos distribution for Delphi