Subscribe

RSS Feed (xml)

Add a Control Programmatically in C#

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);
        }
    }
}

1 comment:

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail