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

后端 未结 1 1173
孤城傲影
孤城傲影 2021-01-03 12:27

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

\"enter

相关标签:
1条回答
  • 2021-01-03 12:48

    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;
    
    0 讨论(0)
提交回复
热议问题