Creating this VCL application consists of the following steps:
- Create a VCL Form with Buttons and ListBox controls.
- Write the code to add strings to a list.
- Write the code to delete a string from the list.
- Run the application.
To create a VCL Form with TButton and ListBox controls
- Choose FileNewOtherDelphi Projects or C++Builder Projects and double-click the VCL Forms Application icon. The VCL Forms Designer is displayed.
- From the Standard page of the Tool palette, place two TButtons and a TListBox component on the form.
- Select Button1 on the form.
- In the Object Inspector, enter Add for the Name and Caption properties.
- Select Button2 on the form.
- In the Object Inspector, enter Delete for the Name and Caption properties.
To add strings to a list
- Select the Add button 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.AddClick (Delphi) or TForm1::AddClick (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 declaration:
For C++, enter the following variable declaration:
- Insert the cursor within the code block, and type the following code:
MyList := TStringList.Create;
try
with MyList do
begin
Add('Mice');
Add('Goats');
Add('Elephants');
Add('Birds');
ListBox1.Items.AddStrings(MyList);
end;
finally
MyList.Free;
end;
MyList = new TStringList();
try {
MyList->Add( “Mice” );
MyList->Add( “Goats” );
MyList->Add( “Elephants” );
MyList->Add( “Birds” );
ListBox1–>Items->AddStrings( MyList );
} __finally {
MyList->Free();
}
To delete a string from the list
- Select the Delete button 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.DeleteClick (Delphi) or TForm1::DeleteClick (C++) event handler block.
- For Delphi, place the cursor before the begin reserved word; then press ENTER. This creates a new line above the code block.
- For Delphi, insert the cursor on the new line created and type the following variable declaration:
For C++, enter the following variable declaration:
- For Delphi, insert the cursor within the code block and type the following code:
with ListBox1.Items do
begin
BIndex := IndexOf('Elephants');
Delete (BIndex);
end;
BIndex = ListBox1–>Items->IndexOf( “Elephants” );
ListBox1–>Items->Delete( BIndex );
To run the application
- Save your project files; then choose RunRun to build and run the application. The form displays with the controls.
- Click the Add button. The strings 'Mice', 'Goats', 'Elephants', and 'Birds' display in the order listed.
- Click the Delete button. The string 'Elephants' is deleted from the list.