Blog

Tagged by 'dynamic controls'

  • I had created some .NET UserControl’s that I needed to dynamically add to a Panel control within my page. I previously thought generating my UserControl’s dynamically would be the same as dynamically generating any other .NET Control, like this:

    private void CreateControls()
    {
        //Create control
        TextBox txtUser = new TextBox();
        txtUser.ID = "txtUser";
        txtUser.Text = "Please enter a value";
     
        //Add Control to Panel already in our .NET page
        pnlControlPlaceHolder.Controls.Add(txtUser);
    }
    

    But I was wrong! :-)

    Fortunately, there is a really easy way to to add a UserControl dynamically by simply making use of the “LoadControl” method. The “LoadControl” method takes a single parameter containing the virtual path of your UserControl. For example:

    private void CreateControls()
    {
        //Create control
        Control myUserControl = LoadControl("MyUserControl.ascx") as MyUserControl;
        myUserControl.ID = "ucMyControl";
     
        //Add Control to Panel already in our .NET page
        pnlControlPlaceHolder.Controls.Add(myUserControl);
    }
    

    Easy!