How to add elements dynamically to a form c # from a class

1

Being more precise, I am trying to add (at the moment) some buttons to a form of c #, my dilemma is that I have no idea how to add these elements from the default class that has all the forms of c # , and the examples that I have seen have not worked for me.

What I have at the moment is a failed attempt with AddOwnedForm.

this.productByUserList = myListProducts;
Point newLoc = new Point(5, 5); // Set whatever you want for initial location
//Se recorre la lista de elementos que quiero agregar, se define una posición por defecto y aunque los botones se agregan no logro que me muestre texto o agregarle estilos propios desde c#
foreach (productByUserObject productOfUser in this.productByUserList)
{
   //Añadir elementos 
   Button buttonTest = new Button();
   buttonTest.Size = new Size(10, 50);
   buttonTest.Location = newLoc;
   buttonTest.Text = productOfUser.name;
   newLoc.Offset(0, buttonTest.Height + 5);
   Controls.Add(buttonTest);
}

What I refer to as the default class is a

// a la clase que se crea junto con el formulario
public partial class productByUserForm : Form
{}

I'm looking for new updates that ask me

    
asked by Alejo Florez 14.11.2018 в 05:03
source

1 answer

1

The context of the code could be this way

public partial class productByUserForm : Form
{

    public void productByUserForm_Load()
    {
        AddOwnedForm();
    }

    private void AddOwnedForm()
    {
        this.productByUserList = myListProducts;
        Point newLoc = new Point(5, 5); 

        foreach (productByUserObject productOfUser in this.productByUserList)
        {
           Button buttonTest = new Button();
           buttonTest.Size = new Size(10, 50);
           buttonTest.Location = newLoc;
           buttonTest.Text = productOfUser.name;
           newLoc.Offset(0, buttonTest.Height + 5);
           this.Controls.Add(buttonTest);
        }
    }

}

As you will see inside the method AddOwnedForm() this code is defined which is invoked from the Load of the form, but you could do it from the click of a button, it is indistinct but it has to be from some event

Also if you want you could do it from the form's constructor, but remember to put the call after InitializeComponent()

To work with the button event you simply define

buttonTest.Click += buttonTest_Click;

and at the form level

public void buttonTest_Click(object sender, EventArgs e){

   Button buttonTest = (Button)sender;

   //resto codigo

}

you can know which button launched the event evaluating the sender

    
answered by 14.11.2018 / 06:05
source