1. Home
  2. Computing & Technology
  3. Delphi Programming

Creating a TString object

By Zarko Gajic, About.com

The TStrings class has a method AddObject that adds a string to the list, and associates an object with the string.

If this object is a string you'll need to represent a string as an Object...

~~~~~~~~~~~~~~~~~~~~~~~~~
type
   TString = class(TObject)
   private
     fStr: String;
   public
     constructor Create(const AStr: String) ;
     property Str: String read FStr write FStr;
   end;

constructor TString.Create(const AStr: String) ;
begin
   inherited Create;
   FStr := AStr;
end;

{
You can than use it to add
strings to any Objects property
like this ...
}
var
   ostr: TString;
begin
   ostr := TString.Create('My string as object') ;
   ListBox1.Items.AddObject('Item string here', ostr) ;
end;

{
To retrieve the string ...
}
  ostr := TString(ListBox1.Items.Objects[0]).Str;

{
Make sure you free the String object
when no longer needed
}
for j := 0 to ListBox1.Items.Count - 1 do
begin
   TString(ListBox1.Items.Objects[j]).Free;
   ListBox1.Items.Objects[j] := nil;
end;
~~~~~~~~~~~~~~~~~~~~~~~~~

Delphi tips navigator:
» Deactivating the default context menu (on TWinControl descendants)
« How to use a dialog window to select a folder

Explore Delphi Programming

More from About.com

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. 2002 Delphi Tips
  7. Creating a TString object

©2008 About.com, a part of The New York Times Company.

All rights reserved.