Search code examples
winformsc++-cli

Unable to add buttons in a panel in Windows Form with C++/CLI


I've tried to add buttons in a panel component programmatically in windows form, but failed.

I want to create buttons just same place to other buttons which are already made. So, firstly, I made a vector including button objects.

And then, created new Button objects and added to the panels which are parent of the buttons. That's why I used this:

button_contol_list.at(i)->Controls->Owner->Controls->Add(newButton);

But this doesn't work. To get a control object of button's parent, how should I do?

private: void createButtonDelegate()
        {
            cliext::vector<Button^> button_contol_list;
            button_contol_list.push_back(btn_Connect);
            button_contol_list.push_back(btn_Calibration);
            button_contol_list.push_back(btn_Frame_Init);
            button_contol_list.push_back(btn_Save_Marker_Position);
            button_contol_list.push_back(btn_Save_Gripper_Angle);
            button_contol_list.push_back(btn_Gripper_Close);
            button_contol_list.push_back(btn_Gripper_Open);
            button_contol_list.push_back(btn_Test_ETC);
            button_contol_list.push_back(btn_Retrieving);
            button_contol_list.push_back(btn_Storing);
            button_contol_list.push_back(btn_Marker_Detection);
            button_contol_list.push_back(btn_Marker_Repeat_Test);
            button_contol_list.push_back(btn_Robot_Connect);
            button_contol_list.push_back(btn_Cam_Connect);
            button_contol_list.push_back(btn_Cam_Calib);
            button_contol_list.push_back(btn_EIH_Calib);


            for (int i = 0; i < button_contol_list.size(); i++) {

                Button^ newButton = gcnew Button();
                newButton->Name = "btn_tmp_" + i.ToString();
                newButton->Text = "Created Button_" + i.ToString();
                newButton->Location = button_contol_list.at(i)->Location;
                
                newButton->Size = System::Drawing::Size(50, 50);

                newButton->BringToFront();
                newButton->Click += gcnew System::EventHandler(this, &Form1::btn_Initialisation_Click);

                button_contol_list.at(i)->Controls->Owner->Controls->Add(newButton);

            }
}

Solution

  • I found the solution by myself.

    button_contol_list.at(i)->Controls->Owner->Controls->Add(newButton);

    should be

    button_contol_list.at(i)->Parent->Controls->Add(newButton);