Question

Assume that I have a multiple objects stored in TO1 : TList then I create multiple TO1 and put all of them in TO2: TList. How can I get the value of selected object in a selected TO1 within TO2 ?

Was it helpful?

Solution

Since TList gives you pointers for each item, you have to cast the items to the proper datatypes:

var
  aList: TList;
  aItem: TMyObject;
begin

  aList := TList(TO2[selectedO2Index]);       // this cast isn't really needed
  aItem := TMyObject(aList[selectedO1Index]); // neither this one!

end;

You can save one variable by doing like this:

var
  aItem: TMyObject;
begin

  // Now the cast to TList is needed!
  aItem := TMyObject(TList(TO2[selectedO2Index])[selectedO1Index]);

end;

Depending on the Delphi version you are using, it would be more comfortable to use either TList<T> or TObjectList<T> generic class. No casts will be needed!

OTHER TIPS

TO1[i] gives your object.

TO2[j] gives your TO1 list.

Thus TO2[j][i] gives also the object.

 type
  TmyObject = class
           text : string;

  end;


procedure TForm2.Button1Click(Sender: TObject);
var
  MotherList : Tlist;
  ChildList : TList;
  obj1 : TmyObject;
begin
//create mother list
MotherList := Tlist.Create;
//create child lista
ChildList := TList.create;


//fill mother list
MotherList.Add(ChildList);    

//fill child list
obj1:= TmyObject.Create;
obj1.text := 'Element 1';
ChildList.Add(obj1);    

//search element of child list within mother list
showmessage(TmyObject(TList(MotherList.Items[0]).Items[0]).text);

obj1.Free;
ChildList.free;
MotherList.free;
end;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top