Delphi: checking selection in Tree View
There is a Tree View with 2 levels of items. I need to add a text of all selected "sub" (level 1) items into a Memo.
for i := 0 to pred(TreeView1.Items.count) do
if (TreeView1.Items.Item[i].Selected) and (TreeView1.Items.Item[i].Level=1)
then
begin
Memo1.Lines.Add(TreeView1.Items.Item[i].Text)
end;
But ho开发者_运维百科w to add all the "sub" items at once without their checking (selected or not) if their parent (level 0) is selected? E.g. I select the 3 items with the level 0 and their children are added into the Memo.
Thanks for help!
Only get level 1 nodes which have a selected parent:
var
Node: TTreeNode;
Sub: TTreeNode;
begin
Node := TreeView.Items.GetFirstNode;
while Node <> nil do
begin
if Node.Selected then
begin
Sub := Node.GetFirstChild;
while Sub <> nil do
begin
Memo1.Lines.Add(Sub.Text);
Sub := Sub.GetNextSibling;
end;
end;
Node := Node.GetNextSibling;
end;
end;
Update due to comment:
Get level 1 nodes which have a selected parent, or are selected themselves:
var
I: Integer;
begin
for I := 0 to TreeView.Items.Count - 1 do
with TreeView.Items[I] do
if (Level = 1) and (Selected or Parent.Selected) then
Memo1.Lines.Add(Text);
end;
It seems to me that you are looking for all selected nodes which have a parent node. The easiest way to do that is as follows:
procedure EnumerateSelectedNonTopLevelItems(TreeView: TTreeView; List: TStrings);
var
Node: TTreeNode;
begin
for Node in TreeView.Items do
if Node.Selected and Assigned(Node.Parent) then
List.Add(Node.Text);
end;
This routine will give you nodes at levels 2, 3, 4 etc. Since you only have level 0 and level 1 this is fine. If you really did need the nodes that are direct descendants of top-level nodes then you can modify the test like this:
if Node.Selected and Assigned(Node.Parent) and not Assigned(Node.Parent.Parent) then
精彩评论