Accidental Technologist

Musings about Entrepreneurship, Technology and Software Development

  • Home
  • About
  • Still River Software
  • Privacy Policy

Powered by Genesis

You are here: Home / ASP.NET / Dynamically Adding User and Web Controls

Dynamically Adding User and Web Controls

September 4, 2005 by Rob Bazinet

Tweet

I often make use of user controls for my web applications.   User controls are nice componentized chunks of HTML and .NET web controls combined and delivered as chunks of reusable code.

Much of the time these controls are dropped on a form much like using a server control.   In my current project I had the pleasure of using user controls dynamically.   Dynamically adding user controls to a form is a bit different than dynamically adding a standard server control.

Dynamically adding a web control:

        public class WebForm1 : System.Web.UI.Page
        {
            // Added by hand; will create instance in OnInit.
            protected System.Web.UI.WebControls.TextBox TextBox1;
            protected System.Web.UI.WebControls.TextBox TextBox2;
 
            override protected void OnInit(EventArgs e)
            {
                // Create dynamic controls here.
                TextBox1 = new TextBox();
                TextBox1.ID = "TextBox1";
                Form1.Controls.Add(TextBox1);
 
                TextBox2 = new TextBox();
                TextBox2.ID = "TextBox2";
                Form1.Controls.Add(TextBox2);
            }        
        }
    }

Dynamically adding a user control:

        private void Page_Init(object sender, System.EventArgs e)
        {
            int index=0;
            foreach (ProgramOptInQuestion poq in poi.Questions)
            {
                TableRow r = new TableRow();
 
                // load the user control. 
                QuestionUI question = (QuestionUI)[email protected]"~\Common\UserControls\Components\QuestionUI.ascx"); 
 
                // This table cell is run server-side and has a Control Collection associated with it.
                // Add the control to this collection.  
                // Could be done in the Page class but done here to allow for positioning.
                TableCell c = new TableCell();
                c.Controls.Add(question);
                r.Cells.Add(c);
 
                // append a new row to our table
                this.QuestionTable.Rows.Add(r);
            }
        }

The purpose of this code is to iterate through a collection of questions and load each question dynamically.

Notice the difference between the  two pieces of code.  Dynamically adding the user control requires the control to be loaded using the LoadControl method.

If you have never added web controls or user controls dynamically, it’s worth noting that the controls are actually added in the OnInit() and added to the Controls collection of an object.

Note – we use the OnInit() to load each web and user control because the Page object has all it’s controls added each time the page is rendered.  The first example adds the Textbox controls to the Controls collection of the form object.  The user controls are added to a cell that has the RunAt="Server" set and therefore has a Controls collection to work with.  This is subtle, but a detail worth noting.

Share this:

  • LinkedIn
  • Twitter
  • Facebook
  • Email
  • More
  • Pinterest
  • Tumblr
  • Pocket
  • Reddit

Related

Filed Under: ASP.NET

Care about your privacy? I do and use Fathom Analytics on this site.

Fathom Analytics

Comments

  1. Paulo says

    November 26, 2006 at 12:32 pm

    I have added dynamically users controls but when i trigger a event like onclick the user control dont responds, why? i tried re-assigning the event but it also doesnt work

    foreach(string strSubProjectCode in arrSubProjectsCodes){

    objInfoViewTree[i] = (InfoViewTree)this.LoadControl(“Info.ascx”);

    objInfoViewTree[i].Visible = true;

    objInfoViewTree[i].EnableViewState = true; TableCell objCell = new TableCell(); objCell.Controls.Add(objInfoViewTree[i]);

    objRow.Cells.Add(objCell);

    tblTreeContainer.Rows.Add(objRow);

    }

  2. Paulo says

    November 26, 2006 at 12:32 pm

    I have added dynamically users controls but when i trigger a event like onclick the user control dont responds, why? i tried re-assigning the event but it also doesnt work
    foreach(string strSubProjectCode in arrSubProjectsCodes){
    objInfoViewTree[i] = (InfoViewTree)this.LoadControl(“Info.ascx”);
    objInfoViewTree[i].Visible = true;
    objInfoViewTree[i].EnableViewState = true; TableCell objCell = new TableCell(); objCell.Controls.Add(objInfoViewTree[i]);
    objRow.Cells.Add(objCell);
    tblTreeContainer.Rows.Add(objRow);
    }

Recent Posts

  • Social Media Times Are Changing
  • It has certainly been a long time…
  • How to Fix Rails Flash Rendering When Using Hotwire
  • Hotwire Fix for CORS Error when using Omniauth
  • Fix Installation of Ruby using rbenv on macOS Big Sur

Categories

Services I Love

HatchBox - Easy Rails Deploys Fathom Analytics
Follow @rbazinet

Rob Bazinet
@rbazinet

  • Great little utility https://t.co/6AgboJv6oI
    about 1 day ago
  • Funny watching the hate to show up in my time line for ChatGPT. People getting defensive about it.
    about 4 days ago
  • I just backed The SaaS Playbook, by Rob Walling on @Kickstarter https://t.co/1FpTWN9c9v
    about 5 days ago
  • This looks like an interesting project. I need to dig in a bit. https://t.co/gacEX9AmEn "Phlex — fast, object-orie… https://t.co/4AUL0Z0SBl
    about 5 days ago
  • I attempted to use ChatGPT today and asked a couple questions it couldn’t answer. I thought it was a magical black… https://t.co/uJGw0CgUAv
    about 5 days ago
  • RSS - Posts
  • RSS - Comments
Find me on Mastodon