How to dynamically create and manage WinForms controls?
- Creating WinForms controls dynamically.
In WinForms, it is possible to dynamically create controls through code. For example, to create a button control, you can use the following code:
Button button = new Button();
button.Text = "Click me";
button.Size = new Size(100, 50);
button.Location = new Point(50, 50);
this.Controls.Add(button);
By using the above code, you can dynamically create a button control on the form and add it to the form’s control collection.
- Managing dynamically created WinForms controls:
Once a control is dynamically created, it can be managed through code. For example, one can modify the control’s properties, add event handlers, and perform other operations.
button.Text = "New text";
button.Click += Button_Click;
Modify the button’s text to “New text” using the above code, and add an event handler Button_Click for the button’s Click event.
Also, if you need to remove dynamically created controls, you can use the following code:
this.Controls.Remove(button);
button.Dispose();
By the aforementioned code, remove the button control from the form’s control collection and release the resources occupied by the button.