TStringBuilderClickCount (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This code demonstrates the use of the TStringBuilder class to build strings in a simple way. The example calculates the number of times the user pressed a button. Example assumes that you have a button on a form and a private variable called FClickCount.

Code

procedure TMainForm.Button1Click(Sender: TObject);
var
  SB: TStringBuilder;
begin
  { Increase the click count for the button. }
  Inc(FClickCount);

  { Create a new instance of TStringBuilder. }
  SB := TStringBuilder.Create();

  { Append the message to the string builder. }
  SB.Append('This button was pressed ').
    AppendFormat('%d times', [FClickCount]);

  { Show a message; use ToString to access the built string. }
  MessageDlg(SB.ToString(), mtInformation, [mbOK], 0);

  { Clear the string builder to allow building another string. }
  SB.Clear();

  if SB.Length <> 0 then
    MessageDlg('This cannot happen! Length must be 0 after clear!', mtError, [mbOK], 0);

  { Build another string with 2 lines. }
  SB.Append('Ne name of the button was:').
    AppendLine().
      Append((Sender as TButton).Name);

  { Show another message and free the string builder instance. }
  MessageDlg(SB.ToString(), mtInformation, [mbOK], 0);
  SB.Free;
end;

Uses