Videos | Podcasts

Loading User Controls Dynamically
AzamSharp
Published Date: 8/25/2005 6:57:32 PM
Views: 5593

Abstract:
User Controls are great in ASP.NET. They let us divide the page into small sections. You can easily use User Controls on a ASP.NET page by simply dragging and dropping the control from the solution explorer. Sometimes we need to load the User Control dynamically. In this small article we will learn how to load the User Control dynamically.

Introduction:

User Controls are great in ASP.NET. They let us divide the page into small sections. You can easily use User Controls on a ASP.NET page by simply dragging and dropping the control from the solution explorer. Sometimes we need to load the User Control dynamically. In this small article we will learn how to load the User Control dynamically.

Loading User Control Dynamically:

There are no tricks involve in loading User Control dynamically and its simple as anything else. All you have to do is to make an instance of the User Control and add it to the Page Controls collection. Let's look at a small example.

private void LoadMyUserControl()

{

// Load the User Controls Dynamically

MyUserControl myControl = (MyUserControl) Page.LoadControl("MyUserControl.ascx");

Page.Controls.Add(myControl);

}

All we are doing is we make an instance of the User Control and simply add the control to the Page Controls collection. Just one thing to note that since you are making it dynamically you need to load it each time the Page_Loads. You can simply put a call to the LoadMyUserControl method inside the InitializeComponent() method.

You can also load the User Control in the the panel control.

private void LoadMyUserControl()

{

// Load the User Controls Dynamically

MyUserControl myControl = (MyUserControl) Page.LoadControl("MyUserControl.ascx");

Panel1.Controls.Add(myControl);

Panel1.DataBind();

}

I hope you liked the article, happy coding!


Similar Articles

Creating 3D Charts Using Microsoft Chart Controls

Getting Started with Microsoft Chart Controls

CSS Sprites Merging Images to Achieve Better Performance

Why Page Event’s not Work:

Caputurig Back Button Event & Force The Page To Load From Server:

 
 
   
 
 

Comments/Feedbacks