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;
}
}