Add Controls at Run Time
| Exam 70-505: Add controls to a Windows Form at run time. |
Contents |
Each control that is located in the Toolbox is a member of the Control class that is part of the System.Windows.Forms namespace. Each of these controls is a class, so therefore you can dynamically create controls in code at runtime. The benefit of this is you have flexibility in the user interface to create complete forms based on an external source such as a configuration file.
Adding a Control to a Form at run time uses a similar method to adding a Control to a Container at run time.
Within a method, first create the control that you wish add to the Form.
Button button1 = new Button();
Secondly initialize the control.
button1.Location = new Point(20,10); button1.Text = "Click Me"; button1.Click += new System.EventHandler(button1_Click);
Thirdly, add the control to the Form.
this.Controls.Add(button1);
Finally add any methods for any events that you are handling.
private void button1_Click(object sender, EventArgs e) { ... }
Adding Controls to Containers
Each of the six Container controls discussed in Manage control layout on a Windows Form adds controls in a similar manner. Below is a summary of each one.
Add a control to a Panel
Button button1 = new Button(); button1.Location = new Point(20,10); button1.Text = "Click Me"; panel1.Controls.Add(button1);
Add a control to a GroupBox
Button button1 = new Button(); button1.Location = new Point(20,10); button1.Text = "Click Me"; groupBox1.Controls.Add(button1);
Add a control to a TabControl
Controls cannot be added to a TabControl, instead they must be added to a TabPage.
Add a control to a TabPage
Button button1 = new Button(); button1.Location = new Point(20, 10); button1.Text = "Click Me"; tabPage1.Controls.Add(button1);
Add a control to a FlowLayoutPanel
Button button1 = new Button(); button1.Location = new Point(20, 10); button1.Text = "Click Me"; flowLayoutPanel1.Controls.Add(button1);
Add a control to a TableLayoutPanel
Button button1 = new Button(); button1.Location = new Point(20, 10); button1.Text = "Click Me"; tableLayoutPanel1.Controls.Add(button1);
Add a control to a SplitContainer
Controls can only be added to one of the Panel controls within the SplitContainer.
Button button1 = new Button(); button1.Location = new Point(20, 10); button1.Text = "Click Me"; splitContainer1.Panel1.Controls.Add(button1);
MSDN references
|

