ItemID - Finding Nodes


A common problem encountered when using TreeViews is finding a node.... Say you want to keep a list of the last few nodes the user clicked, how would you do that?

Actually its relatively simple. Each node is uniquely identified by a ItemID property. The ItemID property is declared as a HTreeItem. HTreeItem is defined in CommCtrl.pas you must include this unit if you want to use HTreeItem.

There are two steps here.

Step 1: Get the Node's ItemID


   iValue := integer(Node.ItemID);
Here I get the node's ItemID and save it as an integer (type-cast is needed).

Step 2: Get a Node from the ItemID


   Node := TreeView.Items.GetNode(  HTreeItem(iValue)  );
Again a type-cast is necessary, this time from an integer to a HTreeItem.


Example App.

Control Caption Name
TButton Add but_Add
TButton Remove but_Remove
TTreeView   tv_eg1
TButton Go but_Go
TEdit   ed_GoTo
TLabel Go To Node Label1

This application is rather pointless, it has no real purpose. It should however show quite clearly how to use ItemIDs.A more practical use of ItemIDs will be demonstrated in the "Linking a TreeView and a ListView".


This example is based on example 1.


   procedure TForm1.tv_eg1Click(Sender: TObject);
   begin
         {If there is no selection then exit}
      if(  tv_eg1.Selected = nil  ) then
         Exit;

         {Get the node's ItemID,
            type-cast it to an integer,
            then convert to a string
            and add it to the TMemo}
      mem_LastNodes.Lines.Add(   IntToStr(  integer(tv_eg1.Selected.ItemID)  )    );
   end;

When a node is selected, first check that there is really a selection. Then get the selected Node's ItemID and display it in the TMemo.


   procedure TForm1.but_GoClick(Sender: TObject);
   var
      iNodeID : integer;
      FoundNode : TTreeNode;
   begin
         {Is there text available?}
      if(  ed_GoTo.Text = ''  ) then
         Exit;

         {Get the ItemID the user entered (as an integer)}
      iNodeID := StrToIntDef(  ed_GoTo.Text,  0  );
      if(  iNodeID = 0  ) then
         Exit;
   
         {Now find the node.
            Type cast the integer to a HTreeItem.  To do this you
               must include  Commctrl.pas!
            Call GetNode}
      FoundNode := tv_eg1.Items.GetNode(  HTreeItem(iNodeID)  );

          {If a node was found,  select it}
      if(  FoundNode <> nil  ) then
         FoundNode.Selected := true;
   end;

A ItemID has been entered in the TEdit. Convert the string to a number, the number to a ItemID and then find the node and select it.






All information on these www pages is copyright (©) 1997 Andre .v.d. Merwe And may not be copied or mirrored without my permission.

(©) 1997 Andre .v.d. Merwe And may not be copied or mirrored without my permission.