Development and Programming
C# and .NET
How To Load User Control Dynamically in ASP.NET?
Let say your web application needs to provide different user interface to different user groups. Or, you want to add additional modules without need to re-deploy complete application. In both example cases, one of the ways to achieve this is by loading of user controls dynamically.
Create a new project with one web page and add PlaceHolder control to web form. Markup code of web page could look like this:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DefaultCS.aspx.cs" Inherits="DefaultCS" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<form id="form1" runat="server">
<asp:PlaceHolder ID="phModule" runat="server"></asp:PlaceHolder>
Now add one web user control to project and name it "MyUserControl.ascx". Add some content to user control. This code example contains one Label control with welcome message:
<%@ Control Language="VB" AutoEventWireup="true" CodeFile="MyUserControl.ascx.cs" Inherits="MyUserControl" %>
<asp:Label ID="Label1" runat="server" Text="Hello, this is My User Control dynamically loaded :)"></asp:Label>
Now, you can write ASP.NET server side code to web page, to dynamically load web user control. Code could look like this:
// We need this namespace to load controls dynamically
public partial class DefaultCS : System.Web.UI.Page
protected void Page_Init(object sender, System.EventArgs e)
// Load control from file "MyUserControl.ascx"
Control myUserControl =(Control)Page.LoadControl("MyUserControl.ascx");
// Place web user control to place holder control
Finally, you can start an example and enjoy in dynamically loaded web user control, like in image bellow:
You can, depending of your needs, load different modules and easy provide different functionality in your ASP.NET web application.
When you load a control into a container control, the container raises all of the added control's events until it has caught up to the current event. However, the added control does not catch up with postback data processing. For an added control to participate in postback data processing, including validation, the control must be added in the Init event rather than in the Load event.
© 2017 Digcode.com. All rights reserved.