TreeNodesAddObject (C++)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example requires two buttons, three TEdits, a label, and a populated TreeView. The following code defines a record type of TMyRec and a record pointer type of PMyRec.

typedef struct MyRec {

 String FName, LName;

} TMyRec;

typedef TMyRec* PMyRec;

Assuming these types are used, the following code adds a node to TreeView1 as the last sibling of the node specified by the Index. A TMyRec record is associated with the added item. The FName and LName fields are obtained from edit boxes Edit1 and Edit2. The Index parameter is obtained from edit box Edit3. The item is added only if the Index is a valid value.


Code

#include <memory>       //For STL auto_ptr class
TMyRec *MyRecPtr;

void __fastcall TForm1::Button1Click(TObject *Sender)
{
  int TreeViewIndex;
  TTreeNodes* items;

  // MyRecPtr will be added as an object to the treeview,
  // so it is OK for MyRecPtr to be deleted in this process.
  MyRecPtr =  new TMyRec;
  MyRecPtr->FName = Edit1->Text;
  MyRecPtr->LName = Edit2->Text;
  TreeViewIndex = StrToInt(Edit3->Text);
  items = TreeView1->Items;
  if (items->Count == 0)
	items->AddObject(NULL, L"Item" + IntToStr(TreeViewIndex), MyRecPtr);
  else if ((TreeViewIndex < items->Count) && (TreeViewIndex >= 0))
	items->AddObject(
	  items->Item[TreeViewIndex],
	  L"Item" + IntToStr(TreeViewIndex) + L"after" + items->Item[TreeViewIndex]->Text,
	  MyRecPtr);
}
/*
After an item containing a TMyRec record has been added, 
the following code retrieves the FName and LName values
associated with the item and displays the values in a label.
*/
void __fastcall TForm1::Button2Click(TObject *Sender)
{
  if (TreeView1->Selected->Data != NULL)
  {
	String FNameStr = PMyRec(TreeView1->Selected->Data)->FName;
	String LNameStr = PMyRec(TreeView1->Selected->Data)->LName;
	Label1->Caption = FNameStr + L" " + LNameStr;
  }
}

TTreeNode *currentNode = NULL;

void __fastcall TForm1::Button3Click(TObject *Sender)
{
//  PMyRec  MyRecPtr;
  TTreeNodes* items;

//  MyRecPtr = new TMyRec;
  // MyRecPtr will be added as an object to the treeview, 
  // so it is OK for MyRecPtr to be deleted in this process.
  std::auto_ptr<TMyRec> MyRecPtr(new TMyRec);
  MyRecPtr->FName = Edit1->Text;
  MyRecPtr->LName = Edit2->Text;
  items = TreeView1->Items;
  if (currentNode != NULL)
	items->AddObject(currentNode, Edit4->Text + L" after " + currentNode->Text, MyRecPtr.get());
}

void __fastcall TForm1::TreeView1MouseDown(TObject *Sender, TMouseButton Button,
      TShiftState Shift, int X, int Y)
{
  THitTests HT;
  if (Sender->ClassNameIs(L"TTreeView"))
  {
	TTreeView *pTV = dynamic_cast<TTreeView *>(Sender);
	HT = pTV->GetHitTestInfoAt(X,Y);
    if (HT.Contains(htOnItem))
	  currentNode = pTV->GetNodeAt(X,Y);
  }
}

void __fastcall TForm1::Button4Click(TObject *Sender)
{
  if (currentNode != NULL)
	Label2->Caption = IntToStr(currentNode->AbsoluteIndex);
}

Uses