2017-02-12 65 views
1

我在「項目管理」中有一項任務。我必須分配也可以是子模塊的模塊,所以我想遞歸地將子模塊附加到模塊。Delphi TTreeNode遞歸追加子節點到父節點

示例:

P(項目)模塊(M1,M2,M3,M4)。 M1模塊下面有子模塊(M1S1,M1S2,M1S3),子模塊1(M1S1)下面可以有多個子模塊(M1S1S1,M1S1S2,M1S1S3)等等。

我已經使用遞歸和TTreeNode完成了這段代碼,但是我感覺問題在於條件語句。

procedure TForm2.BitBtn1Click(Sender: TObject); 

begin 
lGlblProjID := 1; 
lGlblProjName := 'Project'; 
    ADOConnectionListner.Connected := true; 
    try 
    if ADOConnectionListner.Connected then 
    begin 

      RootNode := TreeView2.Items.Add(nil, lGlblProjName); 
      getSubChild(lGlblProjID, RootNode); 

    end; 
    except 
     on E: Exception do 
     begin 
     ShowMessage('Exception Class = ' + E.ClassName); 
     end; 
end; 
end; 

procedure TForm2.getSubChild(var Pid: Integer; var SubRoot: TTreeNode); 
var 
    lcount, I, lcurrentID: Integer; 
    lcurrentName: String; 
    lModuleNode: TTreeNode; 

begin 
    // ShowMessage(IntToStr(Pid)+ ' '+SubRoot.Text); 

    ADOQuery1.SQL.Clear; 
    ADOQuery1.SQL.Add('SELECT * FROM treetab Where parent_id =:value1'); 
    ADOQuery1.Parameters.ParamByName('value1').Value := Pid; 
    ADOQuery1.Active := true; 
    lcount := ADOQuery1.RecordCount; 

    for I := 0 to lcount - 1 do 
    begin 
    lcurrentID := ADOQuery1.FieldByName('id').AsInteger; 
    lcurrentName := ADOQuery1.FieldByName('name').AsString; 
    ShowMessage(' id ' + IntToStr(lcurrentID) + ' dd ' + lcurrentName); // print valu of i 

    if ((lcurrentID <> 0)and (SubRoot.Text <> '')) then  //or 
    begin 
     lModuleNode := TreeView1.Items.AddChild(SubRoot, lcurrentName); 
     getSubChild(lcurrentID, lModuleNode); 
    end else // if 
    // lcurrentID = 0 

ShowMessage('end reached'); 

// TreeView1.Items.AddChild(SubRoot, ADOQuery1.FieldByName('name').AsString); 


ADOQuery1.Next; 
    //********* 
    end; 

end; 

enter image description here

我想檢索爲特定項目的子模塊像在這種情況下,項目與ID = 1只。

+0

什麼「條件語句」你是說您有一個問題,你有什麼關於它是錯的關注? – MartynA

+0

下SSP考慮有1個更多的記錄說S1 然後自去年那麼葉SQL返回零和樹建立半隻 P1 -SP -SSP -S1 然後樹休息。 – user3036212

回答

1

你的問題似乎是非本地ADOQuery1它在每次遞歸調用時都會被清除。因此,您將丟失先前查詢中的所有剩餘記錄。您應該爲查詢結果安排本地存儲。

喜歡的東西(未經測試):

procedure GetSubChild() 
type 
    TTempRecord = record 
    id: integer; 
    name: string; 
    end; 

    TTempArray = array of TTempRecord; 
var 
    lcount, I, lcurrentID: Integer; 
    lcurrentName: String; 
    lModuleNode: TTreeNode; 
    recs: TTempArray 
begin 
    // ... 
    // query the db 
    // ... 
    lcount := ADOQuery1.RecordCount; 

    SetLength(recs, lcount); 
    for i := 0 to lcount-1 do 
    begin 
    recs[i].id := ADOQuery1.FieldByName('id').AsInteger; 
    recs[i].name := ADOQuery1.FieldByName('name').AsString; 
    ADOQuery1.Next; 
    end; 

    for i := 0 to lcount-1 do 
    begin 
    lcurrentID := recs[i].id; 
    lcurrentname := recs[i].name; 
    // ... 
    // add to treeview 
    // call recursively GetSubChild() 
    // ... 
    end; 
end; 
+0

由於您提到的代碼沒有經過測試。我已經測試,它工作正常。謝謝。 – user3036212

+0

@user很高興能幫助到您! –