svět, kde se rodí nová budoucnost   
 
Delphi headDelphi Tips

Additional Data within a StringList


How to append additional data to a string in a StringList, ListBox, Memo or ComboBox. The great thing is that this works in the same way for every VCL class that uses TStings like TMemo, TListbox, TCombobox etc. or other classes that provide a Data property, like TTreeView or TListView

To add strings in a stringlist is very easy:
 
var hSL: TStringList;

begin
 
hSL:= TStringList.Create;
  hSL.Add(
'any string...');

  hSL.Destroy;
end;

Howevery - sometimes you need to add additional information to every string. This can be done by the objects-property:

var hIndex: integer;
//any number that specifies the line

begin
 
hSL.Add('my string');
  hSL.Sort;
  hIndex:= hSL.IndexOf(
'my string');
  hSL.Objects[hIndex] := TStringList.Create;
  TStringList(hSL.Objects[hIndex]).Add(
'substring');
end;


The definition of the object property looks like this:
property Objects[Index: Integer]: TObject;

It takes an index where any object (every delphi class derives from TObject) can be assigned respectively appended. To get the right index we call the function 'IndexOf'. IndexOf only works when the stringlist is sorted. Having the index whe can append a new stringlist.

hSL.Objects[hIndex] := TStringList.Create;

With a typecast this 'sub-stringlist' can be filled:

TStringList(hSL.Objects[hIndex]).Add('any substring');

If you need to parse the sub-stringlist, just do this:

for i:= 0 to hSL.Count - 1 do
  for
ii:= 0 to TStringList(hSL.Objects[i]).Count - 1 do

Memo1.Lines.Add(TStringList(hSL.Objects[i]).
                                          Strings[ii]);


{When the application terminates every substringlist has to be destroyed explicitely}

for i:= 0 to hSL.Count - 1 do hSL.Objects[i].Destroy;

{Now you can destroy the main stringlist itself}
hSL.Destroy;

{Of course you can also define your own 'data-container' that can be appended to every line in the stringlist. Just define a class:}

type
 
TSLData = class
    public
     
X1: integer;
      x2:
string;
     
//etc.
 
end;

  ...

hSL.Objects[hIndex] := TSLData.Create;
TSLData(hSL.Objects[hIndex]).X1 :=
123;
TSLData(hSL.Objects[hIndex]).X2 :=
'123';
 

Back to Index of Tips

 

 

Send mail to radek.novak@infojet.cz with questions or comments about this web site.
Copyright © 1999-2002 Infojet.cz
Last modified: 26.07.2002