TStringBuilderClickCount (C++)

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 m_clickCount.

Code

void __fastcall TMainForm::Button1Click(TObject *Sender)
{
	/* Increase the click count for the button. */
	m_clickCount++;

	/* Create a new instance of TStringBuilder. */
	TStringBuilder* sb = new TStringBuilder();

	/* Append the message to the string builder. */
	sb->Append("This button was pressed ")->
		AppendFormat("%d times", ARRAYOFCONST((m_clickCount)));

	/* Show a message; use ToString to access the built string. */
	MessageDlg(sb->ToString(), mtInformation, TMsgDlgButtons() << mbOK, 0);

	/* Clear the string builder to allow building another string. */
	sb->Clear();

	if (sb->Length != 0)
		MessageDlg("This cannot happen! Length must be 0 after clear!", mtError,
			TMsgDlgButtons() << mbOK, 0);

	/* Build another string with 2 lines. */
	TButton *button = dynamic_cast<TButton *>(Sender);
	sb->Append("The name of the button was:")->
		AppendLine()->
			Append(button->Name);

	/* Show another message and free the string builder instance. */
	MessageDlg(sb->ToString(), mtInformation, TMsgDlgButtons() << mbOK, 0);
	delete sb;
}

Uses

See Also