Microsoft KB Archive/815780

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

Article ID: 815780

Article Last Modified on 11/14/2007

-

APPLIES TO


 * Microsoft Visual C# .NET 2003 Standard Edition
 * Microsoft Visual C# .NET 2002 Standard Edition
 * 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



IN THIS TASK

 * SUMMARY
 * Step-by-step example
 * Code discussion
 * REFERENCES



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.  Start Microsoft Visual Studio .NET or Microsoft Visual Studio 2005. On the File menu, point to New, and then click Project. 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.  Add the following code to the top of the Form1 Code window: using System.Reflection;  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. In the Properties window, change the Name and the Text properties of these controls as follows:

</li>  Paste the following code for the first statements of the definition for Form1: TreeView DynTreeview; TextBox DynTextBox; ListBox DynListBox; Control ControlObject; </li> Switch to Design view, and then double-click Form1 to position the insertion point at the first line of the Form1_Load event.</li>  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]{&quot;TreeView&quot;,&quot;ListBox&quot;,&quot;TextBox&quot;}); </li>  Paste the following code after the &quot;Windows Form Designer generated code&quot; 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(&quot;TreeView&quot;)) {     DynTreeview = (System.Windows.Forms.TreeView)ControlObject; DynTreeview.Width = 200; DynTreeview.Height = 120; DynTreeview.Nodes.Add(new TreeNode(&quot;Root&quot;)); DynTreeview.Nodes.Add(&quot;FirstChild&quot;); DynTreeview.Nodes.Add(&quot;SecondChild&quot;); DynTreeview.ExpandAll; DynTreeview.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(DynTree_AfterSelect); }  else if (ControlType.EndsWith(&quot;ListBox&quot;)) {     DynListBox = (System.Windows.Forms.ListBox)ControlObject; DynListBox.Width = 200; DynListBox.Height = 120; DynListBox.Items.AddRange(new object[3]{&quot;Apples&quot;, &quot;Banana&quot;, &quot;Oranges&quot;}); DynListBox.SelectedIndexChanged += new System.EventHandler(DynCtrl_Event); }  else if (ControlType.EndsWith(&quot;TextBox&quot;)) {     DynTextBox = (System.Windows.Forms.TextBox)ControlObject; DynTextBox.Width = 200; DynTextBox.Text = &quot;Dynamically Added Textbox.&quot;; 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(&quot;Select a Control Type to add.&quot;); return; }

CtrlType = &quot;System.Windows.Forms.&quot; + cboControlType.SelectedItem.ToString; this.AddControl(&quot;myControl&quot;, CtrlType); }

private void DynCtrl_Event(object sender, System.EventArgs e) { if (sender.GetType.ToString.EndsWith(&quot;ListBox&quot;)) {     MessageBox.Show(&quot;The item you selected is: &quot; + DynListBox.SelectedItem.ToString); }  else if (sender.GetType.ToString.EndsWith(&quot;TextBox&quot;)) {     Clipboard.SetDataObject(DynTextBox.Text); MessageBox.Show(&quot;The Text is copied to the clipboard.&quot;); } }

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(&quot;The Node you clicked on is: &quot; + e.Node.Text); } </li> Save your project.</li> To run your project, click Start in the Debug menu.</li> 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.</li></ol>

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

<div class="references_section">