Programming C++Builder Working with string lists (create, load and save a string list) in C++Builder

One of the most commonly used types of list is a list of character strings. Examples include items in a combo box, lines in a memo, names of fonts, and names of rows and columns in a string grid. BaseCLX provides a common interface to any list of strings through an object called TStrings and its descendants such as TStringList and THashedStringList. TStringList implements the abstract properties and methods introduced by TStrings, and introduces properties, events, and methods to

  • Sort the strings in the list.
  • Prohibit duplicate strings in sorted lists.
  • Respond to changes in the contents of the list.

In addition to providing functionality for maintaining string lists, these objects allow easy interoperability; for example, you can edit the lines of a memo (which are a TStrings descendant) and then use these lines as items in a combo box (also a TStrings descendant).
A string-list property appears in the Object Inspector with TStrings in the Value column. Double-click TStrings to open the String List editor, where you can edit, add, or delete lines.

You can also work with string-list objects at runtime to perform such tasks as

Loading and Saving String Lists.

String-list objects provide SaveToFile and LoadFromFile methods that let you store a string list in a text file and load a text file into a string list. Each line in the text file corresponds to a string in the list. Using these methods, you could, for example, create a simple text editor by loading a file into a memo component, or save lists of items for combo boxes.
The following example loads a copy of the WIN.INI file into a memo field and makes a backup copy called WIN.BAK.

void __fastcall EditWinIniFile()
  AnsiString FileName = "C:\\WINDOWS\\WIN.INI"; // set the file name
  Form1->Memo1->Lines->LoadFromFile(FileName);      // load from file
  Form1->Memo1->Lines->SaveToFile(ChangeFileExt(FileName, ".BAK"));  // save to backup

Creating a New String List.

A string list is typically part of a component. There are times, however, when it is convenient to create independent string lists, for example to store strings for a lookup table. The way you create and manage a string list depends on whether the list is short-term (constructed, used, and destroyed in a single routine) or long-term (available until the application shuts down). Whichever type of string list you create, remember that you are responsible for freeing the list when you finish with it.

Short-term string lists

If you use a string list only for the duration of a single routine, you can create it, use it, and destroy it all in one place. This is the safest way to work with string lists. Because the string-list object allocates memory for itself and its strings, you should use a try...__finally block to ensure that the memory is freed even if an exception occurs.

1 Construct the string-list object.
2 In the try part of a try...__finally block, use the string list.
3 In the __finally part, free the string-list object.

The following event handler responds to a button click by constructing a string list, using it, and then destroying it.

void __fastcall TForm1::ButtonClick1(TObject *Sender)

   TStringList *TempList = new TStringList; // declare the list
      //use the string list
    delete TempList; // destroy the list object

Long-term string lists

If a string list must be available at any time while your application runs, construct the list at start-up and destroy it before the application terminates.

1 In the unit file for your application's main form, add a field of type TStrings to the form's declaration.
2 Write a constructor for the main form that executes before the form appears. It should create a string list and assign it to the field you declared in the first step.
3 Write an event handler that frees the string list for the form's OnClose event.

This example uses a long-term string list to record the user's mouse clicks on the main form, then saves the list to a file before the application terminates.


#pragma hdrstop
#include "Unit1.h"
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
   ClickList = new TStringList;

void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action)
   ClickList->SaveToFile(ChangeFileExt(Application->ExeName, ".LOG"));//Save the list
   delete ClickList;
void __fastcallTForm1::FormMouseDown(TObject *Sender, TMouseButton Button,
      TShiftState Shift, int X, int Y)
   TVarRec v[] = {X,Y};
   ClickList->Add(Format("Click at (%d, %d)",v,ARRAYSIZE(v) - 1));//add a string to the list

Associating Objects With a String List.

In addition to the strings stored in its Strings property, a string list can maintain references to objects, which it stores in its Objects property. Like Strings, Objects is an array with a zero-based index. The most common use for Objects is to associate bitmaps with strings for owner-draw controls.
Use the AddObject or InsertObject method to add a string and an associated object to the list in a single step. IndexOfObject returns the index of the first string in the list associated with a specified object. Methods like Delete, Clear, and Move operate on both strings and objects; for example, deleting a string removes the corresponding object (if there is one).

To associate an object with an existing string, assign the object to the Objects property at the same index. You cannot add an object without adding a corresponding string.

Add comment

Security code

Programming - C++Builder