WebUserControl and Dynamic Control Creation

I've a simple web user control, inside it, I've some dropdownlists that I populate and fill them in Page_Init event of page.
When I drag and drop my control on page, it works well and as expected.

But when I try to dynamically add controls to a page, (for example in Page_PreInit event of the page, by coding:
        WebUserControl w = new WebUserControl();
        this.Controls.Add(w);
)

"Object reference not set to an instance of an object." error occurs (for this.DropDownList1.Items.Add("1");)

I think I should read more about Page Life Cycle, but any direct help, would be highly appreciated.
LVL 12
Mortaza DoulatyAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
varungdConnect With a Mentor Commented:
Add a 'PlaceHolder' and try like this.
 

Control FeaturedProductUserControl = LoadControl("WebUserControl1.ascx");
            PlaceHolder1.Controls.Add(FeaturedProductUserControl); 

Open in new window

0
All Courses

From novice to tech pro — start learning today.