How to dynamically add a control without hardcoding the control type in Visual C# .NET or Visual C# 2005 (815780)



The information in this article applies to:

  • Microsoft Visual C# .NET (2003)
  • Microsoft Visual C# .NET (2002)
  • Microsoft Visual C# 2005, Express Edition

For a Microsoft Visual Basic .NET version of this article, see 311321.
This article refers to the following Microsoft .NET Framework Class Library namespace:
  • System.Reflection

SUMMARY

This step-by-step article describes how to dynamically add a control to a form in Visual C# .NET or Visual C# 2005 and how to respond to the events of the control.

back to the top

Step-by-step example

This section describes how to create a project that demonstrates how to dynamically add a control to a form in Visual C# .NET or in Visual C# 2005 and how to respond to the events of the control.
  1. Start Microsoft Visual Studio .NET or Microsoft Visual Studio 2005.
  2. On the File menu, point to New, and then click Project.
  3. Click Visual C# Projects under Project Types, and then click Windows Application under Templates. By default, Form1 is added to the project.

    Note In Visual Studio 2005, click Visual C# under Project Types.
  4. Add the following code to the top of the Form1 Code window:
    using System.Reflection;
  5. Drag two Button controls and one ComboBox control from the toolbox, and then drop the controls near the bottom of Form1. You will add controls dynamically to the top of the form.
  6. In the Properties window, change the Name and the Text properties of these controls as follows:

    ControlNameText Property
    button1btnAddControlAdd Control
    button2btnRemoveControlRemove Control
    comboBox1cboControlTypeSelect Control Type
  7. Paste the following code for the first statements of the definition for Form1:
    TreeView DynTreeview;
    TextBox DynTextBox;
    ListBox DynListBox;
    Control ControlObject;
  8. Switch to Design view, and then double-click Form1 to position the insertion point at the first line of the Form1_Load event.
  9. Paste the following code in the Form1_Load event:
    this.btnAddControl.Click += new System.EventHandler(this.btnAddControl_Click);
    this.btnRemoveControl.Click += new System.EventHandler(this.btnRemoveControl_Click);
    cboControlType.Items.AddRange(new object[3]{"TreeView","ListBox","TextBox"});
  10. Paste the following code after the "Windows Form Designer generated code" region of Form1:
    private void AddControl(string ControlName, string ControlType)
    {
       System.Reflection.Assembly asm;
       asm = typeof(Form).Assembly;
       ControlObject = (System.Windows.Forms.Control)asm.CreateInstance(ControlType);
       ControlObject.Name = ControlName;
       ControlObject.Location = new System.Drawing.Point(20, 20);
       this.Controls.Add(ControlObject);
    
       if (ControlType.EndsWith("TreeView"))
       {
          DynTreeview = (System.Windows.Forms.TreeView)ControlObject;
          DynTreeview.Width = 200;
          DynTreeview.Height = 120;
          DynTreeview.Nodes.Add(new TreeNode("Root"));
          DynTreeview.Nodes.Add("FirstChild");
          DynTreeview.Nodes.Add("SecondChild");
          DynTreeview.ExpandAll();
          DynTreeview.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(DynTree_AfterSelect);
       }
       else if (ControlType.EndsWith("ListBox"))
       {
          DynListBox = (System.Windows.Forms.ListBox)ControlObject;
          DynListBox.Width = 200;
          DynListBox.Height = 120;
          DynListBox.Items.AddRange(new object[3]{"Apples", "Banana", "Oranges"});
          DynListBox.SelectedIndexChanged += new System.EventHandler(DynCtrl_Event);
       }
       else if (ControlType.EndsWith("TextBox"))
       {
          DynTextBox = (System.Windows.Forms.TextBox)ControlObject;
          DynTextBox.Width = 200;
          DynTextBox.Text = "Dynamically Added Textbox.";
          DynTextBox.DoubleClick += new System.EventHandler(DynCtrl_Event);
       }
    }
    
    private void btnAddControl_Click(object sender, System.EventArgs e)
    {
       string CtrlType;
    
       if (!(ControlObject == null))
       {
          btnRemoveControl.PerformClick();
       }
    
       if (cboControlType.SelectedIndex < 0)
       {
          MessageBox.Show("Select a Control Type to add.");
          return;
       }
    
       CtrlType = "System.Windows.Forms." + cboControlType.SelectedItem.ToString();
       this.AddControl("myControl", CtrlType);
    }
    
    private void DynCtrl_Event(object sender, System.EventArgs e)
    {
       if (sender.GetType().ToString().EndsWith("ListBox"))
       {
          MessageBox.Show("The item you selected is: " + DynListBox.SelectedItem.ToString());
       }
       else if (sender.GetType().ToString().EndsWith("TextBox"))
       {
          Clipboard.SetDataObject(DynTextBox.Text);
          MessageBox.Show("The Text is copied to the clipboard.");
       }
    }
    
    private void btnRemoveControl_Click(object sender, System.EventArgs e)
    {
       this.Controls.Remove(ControlObject);
       ControlObject = null;
    }
    
    private void DynTree_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
    {
       MessageBox.Show("The Node you clicked on is: " + e.Node.Text);
    }
  11. Save your project.
  12. To run your project, click Start in the Debug menu.
  13. In the combo box, click TreeView for the control type, and then click Add Control. Note that a new TreeView control is added. Click any node to test the AfterClick event of the TreeView control.
back to the top

Code discussion

  • In this sample, the ComboBox control contains the list of control types to be added dynamically. You populate this list in the Load event of the form.
  • You declared three specific control objects in the initial statements of the definition for Form1 so that you can use the individual functionality of these control objects in your program. By declaring specific control types, you can also access Microsoft IntelliSense while you are programming.
  • In the btnAddControl_Click event handler, you check to determine if there is another control that is already loaded. If so, you remove the existing control and then add the new control that was selected in the combo box. You also make sure that the combo box has a valid selection. If the selection is not valid, the program generates a message box and exits the event handler without processing more statements. If the selection is valid, you call the AddControl method with appropriate parameters.
  • In the AddControl method, you declared asm as a System.Reflection.Assembly type. The typeof(Form) statement returns the type object of the Form type. You then use the Assembly method of this object to retrieve an instance of the assembly where the Form class is defined. After assembly, the asm object is created. You use the CreateInstance method of the asm object with a ControlType string parameter to create an instance of the control. After the control is created, you add it to the current form by using the this.Controls.Add method. Then, by using the EndsWith method of the String class, you check the type of control that is passed to this procedure as the second argument. Depending on the control type, you set the individual properties of the control in the if...else...if... block. You use the += operator to connect the specific event of the dynamically-added control with the event handler. For ListBox and TextBox controls, you connected the SelectedIndexChanged and the DoubleClick events with the DynCtrl_Event event handler. For the TreeView control, you used a separate event handler (DynTree_AfterSelect) to connect the control with the AfterSelect event of the TreeView control.
  • The event-handler for the TreeView control requires a different signature from that of the other two controls. The second argument in the DynTree_AfterSelect event-handler is of type System.Windows.Forms.TreeViewEventArgs; for the DynCtrl_Event event-handler you use type System.EventArgs. The System.Windows.Forms.TreeViewEventArgs type provides additional information, such as the properties of the selected node.
back to the top

REFERENCES

For more information about adding a control on a form if the control type is hardcoded, visit the following Microsoft Developer Network (MSDN) Web site:For more information about event handlers, visit the following MSDN Web site:back to the top

Modification Type:MajorLast Reviewed:1/21/2006
Keywords:kbWindowsForms kbForms kbide kbTreeView kbListBox kbComboBox kbButton kbEvent kbCtrlCreate kbNameSpace kbProgramming kbHOWTOmaster KB815780 kbAudDeveloper