Home Articles Books Downloads FAQs Tips

Q: Create a control at runtime

Step 1: Add a variable to the form class that will contain the component. Since this component is not being managed by the IDE, do not put the declaration in the __published section. Also, make sure the variable is listed as a pointer.

    class TForm1 : public TForm
    {
        __published:   // IDE-managed Components
        private:       // User declarations
            TButton *OKButton;
        ...

Technically, the variable does not have to reside in the form class that the control will appear in. You could place the OKButton declaration in TForm1, even if you will display the button in another form. However, you should avoid this practice for the sake of code clarity.

Step 2: Create the control and assign properties. If you want the control to appear when the form appears, place this code in the constructor of the form.

    __fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
    {
        OKButton = new TButton(this);
        OKButton->Parent  = this;
        OKButton->Caption = "Dynamic Button";
        OKButton->SetBounds(10,10,110,25);
    }

Note: The contol will not appear if you forget to assign the Parent property.

Note: For most dynamic controls, you will need to assign an event handler in code. This task is separated into a different question. See the FAQ listed as how do I assign event handlers at runtime. The example below assigns an OnClick handler for the button.

    // header file
    class TForm1 : public TForm
    {
        __published:   // IDE-managed Components
        private:       // User declarations
            TButton *OKButton;
            void __fastcall ButtonClick(TObject *Sender);
        ...
        ...

    // source file
    __fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
    {
        OKButton = new TButton(this);
        OKButton->Parent  = this;
        OKButton->Caption = "Dynamic Button";
        OKButton->SetBounds(10,10,110,25);

        OKButton->OnClick = ButtonClick;
    }

    void __fastcall TForm1::ButtonClick(TObject *Sender)
    {
        // handler code here
    }


Copyright © 1997-2000 by Harold Howe.
All rights reserved.