Search code examples
delphitreeviewdelphi-7

How to retrieve data from database and display in Ttreeview in delphi


Please help me to populate a tree view from SQL database dynamically. I am very new to delphi

enter image description here

and step by step processes are welcome. I have two table formats given in the picture below and i want to fill the tree view from database accordingly. I searched on other resource sites also but didn't find the solution what i am looking for.

I am stuck. Please help me guys.... Many many thanks in advance.

procedure TForm1.Button1Click(Sender: TObject);
var
  // node : TTreeList;
  i: Integer;
  MyTreeNode1,MyTreeNode2 : TTreeNode;
begin
   with TreeList1.Items do
   begin
        Clear;
        MyTreeNode1 := Add(nil, 'Table');
        ADOTable1.First;
        while ADOTable1 do
        begin
            AddChild(MyTreeNode1,'B') ;
            AddChild(MyTreeNode1,'c');
            Next;
        end;
   end;
end;

Solution

  • Switch to TADOQuery and then try something like this:

    procedure TForm1.Button1Click(Sender: TObject);
    var
      CurrentDeptID, RecordDeptID: Integer;
      RootNode, DeptNode: TTreeNode;
    begin
      CurrentDeptID := 0;
      TreeList1.Items.Clear;
      RootNode := TreeList1.Items.Add(nil, 'Departments');
      DeptNode := nil;
      ADOQuery1.SQL.Text := 'SELECT sd.DeptID, sd.Name, d.Dept FROM SubDepartments sd INNER JOIN Departments d ON (sd.DeptID = d.DeptID) ORDER BY d.Dept, sd.Name';
      ADOQuery1.Open;
      try
        ADOQuery1.First;
        while not ADOQuery1.Eof do
        begin
          RecordDeptID := ADOQuery1.FieldByName('DeptID').AsInteger;
          if (DeptNode = nil) or (RecordDeptID <> CurrentDeptID) then
          begin
            DeptNode := TreeList1.Items.AddChild(RootNode, ADOQuery1.FieldByName('Dept').AsString);
            CurrentDeptID := RecordDeptID;
          end;
          TreeList1.Items.AddChild(DeptNode, ADOQuery1.FieldByName('Name').AsString);
          ADOQuery1.Next;
        end;
      finally
        ADOQuery1.Close;
      end;
    end;