Creating Strings
Go Up to How To Build Windows VCL Applications
Creating this VCL application consists of the following steps:
- Create a VCL Form with TButton and TComboBox controls.
- Write the code to create strings for the TButton OnClick handler.
- Run the application.
To create a VCL Form with TButton and TComboBox controls
- Choose File > New > Windows VCL Application - Delphi or Windows VCL Application - C++Builder.
- From the Standard page of the Tool palette, place a TButton, a TLabel, and a TComboBox component on the form.
To write the create string procedure
- Select Button1 on the form.
- In the Object Inspector, double-click the OnClick action on the Events tab. The Code Editor displays, with the cursor in the TForm1.Button1Click (Delphi) or TForm1::Button1Click (C++) event handler block.
- For Delphi, place the cursor before the begin reserved word; then press RETURN. This creates a new line above the code block.
- For Delphi, insert the cursor on the new line created and type the following variable declarations:
var StringList: TStrings;
- For C++, enter the following variable declarations:
TStrings *StringList;
- Insert the cursor within the code block, and type the following code:
StringList := TStringList.Create; try with StringList do begin Add('Animals'); Add('Cats'); Add('Flowers'); end; with ComboBox1 do begin Width := 210; Items.Assign(StringList); ItemIndex := 0; end; Label1.Caption := 'Flowers has an index of ' + IntToStr( StringList->IndexOf( 'Flowers' ) ); finally StringList.free; end;
- For C++
StringList = new TStringList(); try { StringList->Add( "Animals" ); StringList->Add( "Cats" ); StringList->Add( "Flowers" ); ComboBox1->Width = 210; ComboBox1->Items->Assign( StringList ); ComboBox1->ItemIndex = 0; Label1->Caption = "Flowers has an index of " + IntToStr( StringList->IndexOf( "Flowers" ) ); } __finally { StringList->Free(); }
To run the application
- Save your project files; then choose Run > Run to build and run the application. The form displays with the controls.
- Click the Button. The strings 'Animals', 'Cars', and 'Flowers' display alphabetically in a list in the ListBox. The Label caption displays the message string: 'Flowers has an index value of 2.'
- In the ComboBox, click the arrow to expand the drop-down list. The strings added in the TButton event handler appear.