Board index » cppbuilder » Creating Event Handlers for Dynamically created controls

Creating Event Handlers for Dynamically created controls

Here is how I create controls on a form:

DynamicArray<TButton *> btn;
   btn.Length = 5;

   for (int i = 0; i < 5; i++)
   {
     btn[i] = new TButton(Button1);
     btn[i]->Left = Button1->Left + (80 * i);
     btn[i]->Height = 75;
     btn[i]->Width = 75;
     btn[i]->Top = 18;
     frmMain->InsertControl(btn[i]);
   }

How do I code the OnClick events for each of the dynamically created
buttons? Thanks for any help!!!

George

 

Re:Creating Event Handlers for Dynamically created controls


Quote
<u...@domain.invalid> wrote in message

news:3CEEFF63.8080705@domain.invalid...

Quote
>      frmMain->InsertControl(btn[i]);

You should be setting the Parent property instead, not calling
InsertControl() directly:

    btn[i]->Parent = frmMain;

Quote
> How do I code the OnClick events for each of the dynamically created
> buttons?

    btn[i]->OnClick = ButtonClick;

    void __fastcall TMyForm::ButtonClick(TObject *Sender)
    {
        // do something
    }

If you need to know which button was clicked, you can cast the Sender, ie:

    void __fastcall TMyForm::ButtonClick(TObject *Sender)
    {
        TButton *btn = dynamic_cast<TButton*>(Sender);
        if(btn)
            // do something with btn
    }

Gambit

Re:Creating Event Handlers for Dynamically created controls


Quote
Remy Lebeau [TeamB] wrote:
> <u...@domain.invalid> wrote in message
> news:3CEEFF63.8080705@domain.invalid...

>>     frmMain->InsertControl(btn[i]);

> You should be setting the Parent property instead, not calling
> InsertControl() directly:

>     btn[i]->Parent = frmMain;

>>How do I code the OnClick events for each of the dynamically created
>>buttons?

>     btn[i]->OnClick = ButtonClick;

>     void __fastcall TMyForm::ButtonClick(TObject *Sender)
>     {
>         // do something
>     }

> If you need to know which button was clicked, you can cast the Sender, ie:

>     void __fastcall TMyForm::ButtonClick(TObject *Sender)
>     {
>         TButton *btn = dynamic_cast<TButton*>(Sender);
>         if(btn)
>             // do something with btn
>     }

> Gambit

Thank You very much!!!

Other Threads