ASP.NET Creating User Controls Programatically

User Controls are a great way to share functionality between pages, but sometimes you may want to create one on-the-fly. Although simple to do, there is a trick to doing this…

The User Control
Add a new user control to your website called “UserInfo.ascx” and add a single literal control to it. Set its class name to “UserInfo”:

<%@ Control ClassName="UserInfo" Language="C#" AutoEventWireup="true" CodeFile="UserInfo.ascx.cs" Inherits="UserControls_UserInfo" %>
<asp:Literal ID="litDisplayName" runat="server"/>

In the code-behind file, create a String property called “DisplayName” and assign this value to the literal control’s Text property when the control loads:

public partial class UserControls_UserInfo : System.Web.UI.UserControl
{
  public string DisplayName { get; set; }
  protected void Page_Load(object sender, EventArgs e)
  {
    litDisplayName.Text = DisplayName;
  }
}

The Parent Page
Next, we need to add a reference to this control on the parent page, setting its Control property to point to the relative location of our user control:

<%@ Reference Control="~/UserControls/UserInfo.ascx" %>

Add a place holder to mark the location where the control should appear:

<asp:PlaceHolder ID="PlaceHolder1" runat="server"/>

We can now create instances of the user control by using the ASP namespace:

protected void Page_Load(object sender, EventArgs e)
{
  ASP.UserInfo myControl = new ASP.UserInfo();
  myControl.DisplayName = "Joe Blogs";
  PlaceHolder1.Controls.Add(myControl);
}
Advertisements
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

One Response to ASP.NET Creating User Controls Programatically

  1. DanK says:

    I’ve noticed that most Microsoft Examples use the LoadControl method of instantiation:
    UserInfo myControl = (UserInfo)LoadControl("~/UserControls/UserInfo.ascx");

    However, this relies on specifying the path to the user control a second time. Your use of the ASP namespace seems neater.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s