Creating controls dynamically

I want to know if this is possible in C # winform.

create a control when the button is pressed and place it in the specified location.

I think it's possible

private TextBox txtBox = new TextBox(); private Button btnAdd = new Button(); private ListBox lstBox = new ListBox(); private CheckBox chkBox = new CheckBox(); private Label lblCount = new Label(); 

but the problem is that when the button is pressed, the same controls are created. How to avoid this

What yes ........ I wrote, and I did not expect this exception, because the control already has btnAdd , since many buttons create as many as you want. Access to them will be a problem, but it will be solved by @drachenstern method correctly?

  private void button1_Click_1(object sender, EventArgs e) { Button btnAdd = new Button(); btnAdd.BackColor = Color.Gray; btnAdd.Text = "Add"; btnAdd.Location = new System.Drawing.Point(90, 25+i); btnAdd.Size = new System.Drawing.Size(50, 25); this.Controls.Add(btnAdd); i = i + 10; } 
+4
source share
3 answers

You can try the solution that I posted here . It will dynamically create 5 buttons in the constructor. Just move the code to the button click event, and it should dynamically add buttons and register with Click events.

+3
source
 int currentNamingNumber = 0; txtBox.Name = "txtBox" + currentNamingNumber++; 

Rinse, repeat.

Gives each element a unique numeric name, lets you know how many elements were created (note that you do not want to reduce to track all created objects, because then you can create two elements with the same name).

I don’t think you can pass the name you want to the new function, but you can always set the name after creating it.

+3
source

It looks like you are looking for a List<TextBox> .

+2
source

Source: https://habr.com/ru/post/1335916/


All Articles