After Creating a Control, automatically add it to specific panel

127 views Asked by At

I have UserControls that are "Buttons" for Menu purposes. Those Buttons shall automatically add to the right Panel.

So basically, if I write:

MenueButton button1 = new MenueButton();

the button shall automatically be added to MenuePanel on GUI Form. (Maybe Some easy action handler?)

Is there a way to achieve this?

1

There are 1 answers

4
George Vovos On BEST ANSWER

Try something like

 MenueButton button1 = CreateButton();
 button1.Click+=...

 MenueButton button2 = CreateButton();
 button2.Text="ABC";

 MenueButton CreateButton()
 {
   MenueButton b= new MenueButton();
   panel.Controls.Add(b);
   return b;
 }

This way the CreateButton function creates and automatically adds the button to the panel and you can use the newly created button in your code

If you want to do the same thing to the buttons you can add parameters to your function

MenueButton button1 = CreateButton("Button 1 Text");
button1.Click+=... 

MenueButton button2 = CreateButton("XYZ");


MenueButton CreateButton(string buttonText)
{
    MenueButton b= new MenueButton();
    b.Text = buttonText;
    panel.Controls.Add(b);
    return b;
}