Create runtime textboxes

Asked

Viewed 1,618 times

2

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

The problem is that as I don’t want to put only one piece of equipment or a limited amount, I want to have a button that every time the user click on it, add 2 new ones textboxes (Watts consumed by the equipment and the amount of hours per day it stays on), but I have no idea how to do that.

And if possible, also a button that appears next to the new textboxes excluding her.

EDIT: Follow the code I made (It’s quite 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);
    }

}
  • 3

    Winforms or WPF?

2 answers

3

If 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 added fields, ie changing position for one not to overwrite the other.

By clicking the button, the function AddNewTextBox() is called, and she’s responsible for adding the two TextBox() in the Form. Note that the counter also serves to change the Name and the Textof each TextBox().

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

Source: How to create Dynamic Controls in C#

Editing

As the comment of @jbueno, it is worth noting that the above code does not check the size of the form, ie it adds the components without checking if it has space for them.
One way to "solve" this problem is to check the size of the Form and if you pass, do something. Below I will put the code only to check already 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;
        }
    }
  • And when the form size runs out? P

  • 1

    @jbueno You sit and cry. kkkk Scroll. I’ll edit the answer

  • hahah quiet, you can define the AutoScroll form as true.

  • @jbueno I left an alternative "blank", so you can choose what you want to do if it happens.

  • 1

    Ah, it’s much better than spoiling the entire layout of the form with a scroll.

  • Thanks for your help, but I’ve got one more little problem... I don’t know how to put the value of the new textbox in the final result and I also want to know how I can push down as I add more txtboxes the button I did to calculate the result and the textbox I did to show the result. If necessary, I can post the code I’ve done so far here! Ty!

  • @Felipe The way it is, jbueno’s answer is the most appropriate, as it will create a scroll keeping its layout intact. To get the values, you’ll need to go through all the textbox , something how that and do the calculations. Well, without having your code and understanding right what you want, I can only help with that.

  • Code posted.

  • @Felipe could post a print of how is your layout?

  • http://image.prntscr.com/image/d69c2b1ff08c4de0ab759da8b052c7b1.png

  • @Felipe got a little confused. It would be like doing a print of how you want it to look?

  • @Felipe E at the end, daily and monthly consumption, will add all equipment?

  • (http://image.prntscr.com/image/72e176c5478d40c680fc02f83a07c1da.png) In short, I want every time I add new equipment, the area where the calculate button is and the daily consumption is pushed down, so that the new equipment does not lag behind the result. But , really, as you said his answer is the most appropriate, would be easier ... But then the only problem that remains is how I will calculate the result of each textbox that is added, because if it were a certain amount it would be easier... In the end it will take the consumption of each and add up everything.

  • @Felipe Use his answer with this one: http://stackoverflow.com/questions/3419159/how-to-get-all-child-controls-of-a-windows-forms-of-a-specific-type-button/3426721#3426721

  • This way you will calculate the values by clicking to calculate

  • @Felipe But if you want help, implement what we have shown now and open another question on how to add and show the result the way you want, it will be easier for your understanding.

Show 11 more comments

3


The @Randrade reply perfectly answers your question. Since I had already started writing an example, I’ll leave my tip here:

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

First, I added a panel to form and set the property AutoScroll as true, so that it is possible to add as many Textboxes as necessary and that this does not end up ruining the other components in the form.

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

private const int TextBoxX = 5;                //Posição horizontal do textbox no painel
private const int TextBoxWidth = 300;          //Largura do textbox
private const int ButtonX = TextBoxWidth + 10; //Posição horizontal do button no painel
private int _controlY = 5;                     //Posição vertical 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;
}
  • Much cleaner. p +1

  • It is the "beloved" custom with winforms =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.