Search code examples
c++c++buildervcl

C++Builder VCL array of buttons dynamically made each with his independent click action


i have tried the following way but it doesn't seem to work and it is incomplete.

void __fastcall TForm1::Button1Click(TObject *Sender) 
{
    TButton **ButtonArray = NULL;
    ButtonArray = new TButton*[5];

    for(int x = 0; x < 5; ++x) 
    {
        ButtonArray[x] = new TButton(this);
        ButtonArray[x]->Caption = (AnsiString)"teste " + x + " - " + (1+random(100));
        ButtonArray[x]->Left = 25 + 4 * random(100);
        ButtonArray[x]->Top = 25 + 4 * random(100);
    }
}

Code compiles without problems, but no button seems to show. Also, there is no action and buttons in the array have a predefined max of 5.


Solution

  • To make them visible in your form you must set the Parent property of your buttons.

    ButtonArray[ x ]->Parent = this;
    

    There's no action because you do not set one.

    void __fastcall TForm1::ButtonClick(TObject *Sender)
    {
       MessageBox( Handle, L"Hello", L"Message", MB_OK );
    }
    

    And when creating your buttons...

    ButtonArray[ x ]->OnClick = ButtonClick;