6.1 Add a Control Programmatically


Problem

You need to add a control to a form at runtime, not design time.

Solution

Create an instance of the appropriate control class. Then add the control object to a form or a container control using the Add method of the ControlCollection .

Discussion

In a .NET Windows-based application, there's really no difference between creating a control at design time and creating it at runtime. When you create controls at design time (using a tool like Microsoft Visual Studio .NET), the necessary code is added to your form class, typically in a special method named InitializeComponent . You can use the same code in your application to create controls on the fly. Just follow these steps:

  1. Create an instance of the appropriate control class.

  2. Configure the control properties accordingly (particularly the size and position coordinates).

  3. Add the control to the form or another container.

  4. In addition, if you need to handle the events for the new control, you can wire them up to existing methods .

Every control provides a Controls property that references a ControlCollection that contains all of its child controls. To add a child control, you invoke the ControlCollection.Add method. The following example demonstrates this by dynamically creating a list of check boxes. One check box is added for each item in an array. All the check boxes are added to a panel that has its AutoScroll property set to true , which gives basic scrolling support to the check box list.

 using System; using System.Windows.Forms; public class DynamicCheckBox : System.Windows.Forms.Form {     // (Designer code omitted.)     private void DynamicCheckBox_Load(object sender, System.EventArgs e) {              // Create the array.         string[] foods = {"Grain", "Bread", "Beans", "Eggs",           "Chicken", "Milk", "Fruit", "Vegetables",           "Pasta", "Rice", "Fish", "Beef"};         int topPosition = 10;         foreach (string food in foods)         {             // Create a new check box.             CheckBox checkBox = new CheckBox();             checkBox.Left = 10;             checkBox.Top = topPosition;             topPosition += 30;             checkBox.Text = food;             // Add the check box to the form.             panel.Controls.Add(checkBox);         }     } } 

Figure 6.1 shows how the form will look.


Figure 6.1: A dynamically generated check box list.



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net