Sunday, April 13, 2008

Can Objects be assigned to a TStringList?

Well if someone asks that can we store an object in a TStringlist or should we use only TList for this purpose, the answer should be ----> Yes ofcourse!.

Now how to do that and where can I use such facility. Now first to answer why should we require this feature if at all. One place where we can use such a feature is when we are required to save or associate an object to a particular name, like saving a location name with the corresponding bitmap.

Now coming to how to do that in delphi. The answer is using the Objects property associated with TStringlist. Delphi gives the power of associating objects to tstringlist using this simple property.


Please see the below example to see how to do that -

Here in this example add a button to a simple delphi form. Now add two edit texts and add a TMemo component. Now write the following code on the button click event -

procedure TForm1.Button2Click(Sender: TObject);
var
mystringlist : tstringlist;
begin
Memo1.clear;
mystringlist := tstringlist.create();
mystringlist.Add(edit1.text);
mystringlist.Objects[0] := edit1;
mystringlist.Add(edit2.text);
mystringlist.objects[1] := edit2;
memo1.Lines.Add(TEdit(mystringlist.objects[0]).name);
memo1.Lines.Add(TEdit(mystringlist.objects[1]).name);
end;

Run the delphi program by pressing F9 key or navigating to "Run" Menu and clicking on "Run" Menu item.

Now click on the button on the form and you will see that memo displays two strings edit1 and edit2. Here the names have been derieved from the objects stored in the stringlist.

This was just a demonstration program and the power of such a feature can be easily utilized in performing complex tasks.