Please help me to populate a tree view from SQL database dynamically. I am very new to delphi
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;