Create textboxes at runtime

2

I have a project that basically is a program that calculates the electricity consumption of various equipment that I am creating in VS2013.

The problem is that since I do not want to put just one piece of equipment or a limited quantity, I want it to have a button that every time the user clicks it, add 2 new textboxes (Watts consumed by the equipment and amount of hours per day that it stays connected), however I have no idea how to do this.

And if possible, also a button that appears next to the new textboxes that excludes it.

EDIT: Follow the code I made (It's pretty simple)

public partial class Form1 : Form
{

    public Form1()
    {
        ConsumoDiario = 0.0;
        ConsumoMensal = 0.0;
        Ultimonumero = 0.0;
        Horas = 0.0;
        InitializeComponent();
        mtbconsumo.Text = "0";
        mtbhrs.Text = "0";
    }

    private void Calcular(object sender, EventArgs e)
    {
        if (mtbconsumo.Text == "")
            Ultimonumero = 0;
        else
            Ultimonumero = Convert.ToDouble(mtbconsumo.Text);
        if (mtbhrs.Text == "" )
            Horas = 0;
        else
        Horas = Convert.ToInt32(mtbhrs.Text);

        ConsumoDiario = (Ultimonumero * Horas) / 1000;
        ConsumoMensal = ConsumoDiario * 30;
        mtbConsumoD.Text = Convert.ToString(ConsumoDiario);
        mtbConsumoM.Text = Convert.ToString(ConsumoMensal);
    }

}
    
asked by anonymous 27.06.2016 / 18:11

2 answers

2

@Randrade's answer responds perfectly to your question. As I had already started to write an example, I will leave here my tip:

The approach I use is very similar to that in the other answer.

First of all, I added a panel to the form and set the AutoScroll property to true , so that you can add as many TextBoxes as needed and it will not ruin the other components in form.

Here is the code used to create the components, it's all very simple, there's no mystery at all.

private const int TextBoxX = 5;                //Posição vertical do textbox no painel
private const int TextBoxWidth = 300;          //Largura do textbox
private const int ButtonX = TextBoxWidth + 10; //Posição vertical do button no painel
private int _controlY = 5;                     //Posição horizontal dos controles

public Form1()
{
    InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
    panel1.Controls.AddRange(new Control[]
    {
        new TextBox
        {
            Location = new Point(TextBoxX, _controlY),
            Size = new Size(300, 20)
        },

        new Button
        {
            Text = "Texto",
            Location = new Point(ButtonX, _controlY),
            Size = new Size(100, 20)
        }
    });

    _controlY += 25;
}
    
27.06.2016 / 18:51
3

If you're using WinForms , just do it this way:

  public partial class Form1 : Form
    {
        //Contador de botões para definir posição e demais propriedades
        int contador = 1;

        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //Função chamada ao click do botão
            AddNewTextBox();
        }

        public void AddNewTextBox()
        {
            //Define posição top
            var top = contador * 25;

            //Novo textBox watts
            TextBox txt = new TextBox();
            txt.Top = top;
            txt.Left = 10;
            txt.Text = "Watts  " + this.contador.ToString();
            txt.Name = "watts" + contador;
            //Adiciona no Form
            this.Controls.Add(txt);

            //Novo textBox Consumo
            TextBox txt1 = new TextBox();
            txt1.Top = top;
            txt1.Left = 110;
            txt1.Text = "Consumo  " + this.contador.ToString();
            txt1.Name = "consumo" + contador;
            //Adiciona no Form
            this.Controls.Add(txt1);

            //Incrementa Contador
            contador = contador + 1;
        }
    }

In this code we have a counter that helps to define the layout of the fields added, ie, changing position to one does not overwrite the other.

When you click the button, the AddNewTextBox() function is called, and it is responsible for adding the two TextBox() to Form . Note that the counter is also used to change the Name and Text of each TextBox() .

Note that the function is adding TextBox() , but any element can be added to Form or to another element, such as Panel for example.

Source: How to create Dynamic Controls in C #

Issue

According to the comment from @ jbueno , it is worth mentioning that the code above does not check the size of the form, that is, it adds the components without checking if there is room for them. One way to "solve" this problem is to check the size of Form and if it does, do something. Below I will put the code just to verify you have reached the limit, and return a message if yes. But you can do whatever you want.

 public partial class Form1 : Form
    {
        //Contador de botões para definir posição e demais propriedades
        int contador = 1;
        //Tamanho do form
        int width = 0;

        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //Função chamada ao click do botão
            AddNewTextBox();
        }

        public void AddNewTextBox()
        {
            //Adiciona o tamanho do firm
            width = this.Width;

            //Define posição top
            var top = contador * 25;

            //Verifica se irá ultrapassar o form
            if (top >= width)
            {
                MessageBox.Show("Seu Form não tem tamanho para adicionar esse item");
                return;
            }

            //Novo textBox watts
            TextBox txt = new TextBox();
            txt.Top = top;
            txt.Left = 10;
            txt.Text = "Watts  " + this.contador.ToString();
            txt.Name = "watts" + contador;
            //Adiciona no Form
            this.Controls.Add(txt);

            //Novo textBox Consumo
            TextBox txt1 = new TextBox();
            txt1.Top = top;
            txt1.Left = 110;
            txt1.Text = "Consumo  " + this.contador.ToString();
            txt1.Name = "consumo" + contador;
            //Adiciona no Form
            this.Controls.Add(txt1);

            //Incrementa Contador
            contador = contador + 1;
        }
    }
    
27.06.2016 / 18:40