Passing Additional Arguments to Forms

From RAD Studio
Jump to: navigation, search

Go Up to Using Forms

Typically, you create forms for your application from within the IDE. When created this way, the forms have a constructor that takes one argument, Owner, which is the owner of the form being created. (The owner is the calling application object or form object.) Owner can be nil.

To pass additional arguments to a form, create a separate constructor and instantiate the form using this new constructor. The example form class below shows an additional constructor, with the extra argument whichButton. This new constructor is added to the form class manually.

TResultsForm = class(TForm)
  ResultsLabel: TLabel;
  OKButton: TButton;
  procedure OKButtonClick(Sender: TObject);
  constructor CreateWithButton(whichButton: Integer; Owner: TComponent);
class TResultsForm : public TForm {
__published: // IDE-managed Components

	TLabel *ResultsLabel;
	TButton *OKButton;

	void __fastcall OKButtonClick(TObject *Sender);

private: // User declarations

public: // User declarations
	virtual __fastcall TResultsForm(TComponent* Owner);
	virtual __fastcall TResultsForm(int whichButton, TComponent* Owner);

Here's the manually coded constructor that passes the additional argument, whichButton. This constructor uses the whichButton parameter to set the Caption property of a Label control on the form.

constructor CreateWithButton(whichButton: Integer; Owner: TComponent);
  inherited Create(Owner);
  case whichButton of
    1: ResultsLabel.Caption := "You picked the first button.";
    2: ResultsLabel.Caption := "You picked the second button.";
    3: ResultsLabel.Caption := "You picked the third button.";
void__fastcall TResultsForm::TResultsForm(int whichButton, TComponent* Owner)
	: TForm(Owner) {
	switch (whichButton) {
	case 1:
		ResultsLabel->Caption = "You picked the first button!";
	case 2:
		ResultsLabel->Caption = "You picked the second button!";
	case 3:
		ResultsLabel->Caption = "You picked the third button!";

When creating an instance of a form with multiple constructors, you can select the constructor that best suits your purpose. For example, the following OnClick handler for a button on a form calls creates an instance of TResultsForm that uses the extra parameter:

procedure TMainForm.SecondButtonClick(Sender: TObject);
  rf: TResultsForm;
  rf := TResultsForm.CreateWithButton(2, self);
void __fastcall TMainMForm::SecondButtonClick(TObject *Sender) {
    TResultsForm *rf = new TResultsForm(2, this);
    delete rf;

See Also