TStringList


TStringList enables you to store unlimited amount of strings. TStringList combines
the ease of using string arrays and memory flexibility which exists in linked lists.


Declaring string lists :


You can declare string list any where: as a global variable in units, as a local
variable in procedure or functions, or inside objects.

Example :

var
MyList: TStringList;


Creating list objects

You can not use string list - as any other Delphi object - until you create it and
initialize it. Creation of string lists depends on declaration scope, if you declare
it as a global variable you need to create an instance of it only one time, for example
you can create it at main form's
OnCreate event such as:

MyList:= TStringList.Create;

If you want to create a temporary string list in some procedures or functions you
must create the list each time procedure or function is called, but make sure that
you free it when procedure or function finished.

Example:

procedure Test;
var
 MyList: TStringList;
begin
MyList:= TStringList.
Create;
....
....
// After finishing
MyList.
Free;
end;


Adding items to list

Simply use
Add method which addes new string items at the end of list such as:

 MyList.Add('This is a test');

If you want to insert items between certain index you can use
Insert method such
as:

 MyList.Insert(2, 'This will be item # 3');
MyList.
Insert(0, 'This will be first item');


Deleting items from list

Items can be deleted using it's index such as:

 MyList.Delete(2); // Will delete third item


Accessing items in list

Items in string list can be accessed using it's index such as:

 ShowMessage(MyList[0]);

This will display first item. Also you can change an item such as:

 MyList[1]:= 'Second';

But you can not add new item using this method, for example, suppose that you have
a list containing 5 elements from 0 to 4 and you want to add item number 5, it you
write this:

 MyList[5]:= 'New item';

It will rais an exception, instead you have to write:

 MyList.Add('New item');


See also:

Ex004: ListBox
TList and user defined type