70-526 MCTSAdd controls to a Windows Form at run timeEach 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 ContainersEach of the six Container controls discussed in section 1-2 adds controls in a slightly different manner. Below is a summary of each one. Add a control to a Panel TextBox textBox1 = new TextBox(); // Initialize the TextBox control textBox1.Location = new Point(16,32); textBox1.Text = ""; textBox1.Size = new Size(152, 20); // Add the TextBox control to the Panel panel1.Controls.Add(textBox1); Add a control to a GroupBox Button button1 = new Button(); // Initialize the Button control button1.Location = new Point(20,10); button1.Text = "Click Me"; // Add the Button to the GroupBox 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 // Create buttons Button button1 = new Button(); button1.Location = new Point(20, 10); button1.Text = "Click Me"; // Add buttons to TableLayoutPanel tableLayoutPanel1.Controls.Add(button1); Add a control to a SplitContainer Controls can only be added to one of the Panel controls within the SplitContainer. TreeView treeView1 = new TreeView(); treeView1.Dock = DockStyle.Fill; treeView1.ForeColor = SystemColors.InfoText; treeView1.Location = new System.Drawing.Point(0, 0); treeView1.Name = "treeView1"; // Add TreeView control to Panel1 of SplitContainer splitContainer1.Panel1.Controls.Add(treeView1); MSDN references
|