Button creation per cycle

0

How about, I'm doing a cycle to create a certain number of buttons and indeed they are created but I can not make every 5 buttons make a line break, I tried with an if condition but it does not work

// Declaramos el Button y un literal que nos servirá para hacer saltos de línea
            Button bt;
            Literal lt;

            // Por ejemplo crearemos 5 botones, 
            // pero nuestra fuente de información puede ser cualquier otra
            for (int i = 0; i < 101; i++)
            {
                // Inicializamos el botón
                bt = new Button();

                // Le asignamos un text
                bt.Text = "Botón " + i;

                // Hacemos que maneje el evento Click mediante la función bt_Click
                bt.Click += new EventHandler(bt_Click);

                // Inicializamos el literal y hacemos que sea un salto de línea HTML
                lt = new Literal();
                lt.Text = "<tr />";

                // Ubicamos ambos controles en el PlaceHolder que hemos puesto en nuestra página
                // El uso del PlaceHolder no es obligatorio ni mucho menos, 
                // podéis añadir los controles donde os haga falta: 
                // una Cell de un Table, un Panel, a la propia Page, etc.
                Panel1.Controls.Add(bt);
                Panel1.Controls.Add(lt);
            }
    
asked by Cesar Gutierrez Davalos 21.06.2017 в 22:36
source

1 answer

1

The declaration of the controls must be placed inside the loop

for (int i = 0; i < 101; i++)
{

    Button bt = new Button();
    btn.Location = new Point(...);
    bt.Text = "Botón " + i;
    bt.Click += new EventHandler(bt_Click);

    Literal lt = new Literal();
    lt.Location = new Point(...);
    lt.Text = "<tr />";

    Panel1.Controls.Add(bt);
    Panel1.Controls.Add(lt);
}

analyze how the variable is defined and the instance is assigned when using

Button bt = new Button();

do not declare globally since you would be stepping on each iteration the previous instance, remember that the objects will be created by reference

You also remember to assign the property Location of the controls, otherwise they will appear one on top of the other

Control.Location Property

    
answered by 21.06.2017 в 22:50