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 Text
of 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;
}
}
Winforms or WPF?
– Jéf Bueno