web analytics

How To Load User Control Dynamically in ASP.NET?

Options

codeling 1599 - 6654
@2017-02-08 16:04:22

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">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:PlaceHolder ID="phModule" runat="server"></asp:PlaceHolder>
   
    </div>
    </form>
</body>
</html>

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
using System.Web.UI;
 
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
        phModule.Controls.Add(myUserControl);
 
    }
}

Finally, you can start an example and enjoy in dynamically loaded web user control, like in image bellow:

Web user control loaded at run time

You can, depending of your needs, load different modules and easy provide different functionality in your ASP.NET web application.

@2017-02-08 16:12:09

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.

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com