Code: Adding Controls at Run Time (Visual C#)

Code: Adding Controls at Run Time (Visual C#)

Visual Studio .NET 2003

This example adds a text box and button to a Web Forms page at run time. It also dynamically binds an event handler to the button's Click event. The handler displays the values of the dynamically generated text box.

The controls are added into a Panel Web server control, which acts as a placeholder. The controls are separated in the panel with line breaks (HTML <BR> elements), which are added to the panel using the LiteralControl control.


private void Page_Load(object sender, System.EventArgs e)
    if (!IsPostBack)

protected override void LoadViewState(object savedState)
    if (ViewState["controsladded"] == null)

private void AddControls()
    TextBox dynamictextbox = new TextBox();
    dynamictextbox.Text = "(Enter some text)";
    dynamictextbox.ID = "dynamictextbox";
    Button dynamicbutton = new Button();
    dynamicbutton.Click += new System.EventHandler(dynamicbutton_Click);
    dynamicbutton.Text = "Dynamic Button";
    Panel1.Controls.Add(new LiteralControl("<BR>"));
    Panel1.Controls.Add(new LiteralControl("<BR>"));
    ViewState["controlsadded"] = true;

private void dynamicbutton_Click(Object sender, System.EventArgs e)
    TextBox tb = new TextBox();
    tb = (TextBox) (Panel1.FindControl("dynamictextbox"));
    Label1.Text = tb.Text;

Compiling the Code

This example requires:

  • A Web Forms page.
  • A Panel control called Panel1.
  • A Label control called Label1.


User input in a Web Forms page can include potentially malicious client script. By default, the Web Forms page validates that user input does not include script or HTML elements. For more information, see Scripting Exploits and Protecting Against Script Exploits in a Web Application.

See Also

Adding Controls to a Web Forms Page Programmatically | Code: Reading a Value From View State (Visual C#) | Code: Saving a Value in View State (Visual C#) | Introduction to Web Forms State Management | Referencing Controls in Web Forms Pages | Web Applications Example Topics

© 2015 Microsoft