[ASP.NET] Custom Controls – User Controls

“Code Reuse” is the phrase you have heard hundreds of times as a developer. ASP.NET server controls provides you with the basic building blocks for the web pages. But they are general controls and are not quite customized for your business needs.

There are 2 ways you can create your own web server controls. The first approach is to create a custom web control. You are responsible to generate HTML code. But in most cases, you do not need a custom web server control. Rather you can create a set of existing controls as a one unit (control) and reuse it whenever you want.  

1. User Controls

A user control enables a developer to easily combine ASP.NET controls into a single control for encapsulating common functionality.

  • A user control cannot be compiled to its own .dll and shared. It can only be shared within a single site
  • You can expose properties, events, and methods
  • A user control follows the same life cycle as a Page

You can create a new user control by selecting “Add New Item > Web User Control“.

  • A user control inherits from the “System.Web.UI.UserControl” class
  • “@Control” directive instead of “@Page” directive

2. Adding User Controls to a Page

User controls are not requested directly by users, and should be embedded in a page. Actually, it is very easy to add a user control to a page in VS. You can just drag the ascx file into the web page (Design Screen).

If you can do it manually or add a user control dynamically in you code, follow the steps in the below:

  • Add a “@Register” directive
  • Add a user control statically or dynamically

The “@Register” directive has the following attributes

  • assembly: the assembly in which the namespace associated with the tagprefix attribute resides
  • namespace: the namespace of the custom control that is being registered
  • src: the location of the user control file
  • tagname: an arbitrary alias to the control
  • tagprefix: an arbitrary prefix markup
<@Register src="MyUC.ascx" tagname="MyUC" tagPrefix="uc1" />

When you add a control statically, the tagprefix and the tagname is used.

<uc1:MyUC ID="myUC1" runat="server" MyProperty="data" />

When you load a control dynamically, you can use the “Page.LoadControl()” method.

MyUC myUC1 = (MyUC) LoadControl("MyUC.ascx");
form1.Controls.Add(myUC1);

3. User Control Events

The tricky part of the user control is to handle events. If the user control is completely independent with a host page, it is ok. But what if your page and user control need to interact with each other. First way is to use public properties and the second way is to use event handlers. Suppose a host page wants to do something when a button in a user control is clicked. The event handler for a button is located in the user control. How a page can react this?

The trick is simple.

  • Create a event in a user control (method delegate)
  • Inside the user control’s event handler, calls the event
  • When a user control is created in a page, the event handler in the page is passed to the user control
  • If you need to pass information from a user control to a page, you can create a custom event argument object

Look at the example in the next section.

4. User Control Example

Let’s create a login control.

– Custom event arguement class –

public class LoginEventArgs : EventArgs
{
    public bool IsAuthenticated { get; set; }
}

– User control –

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UserLogin.ascx.cs" Inherits="WebApp.UserLogin" %>
User ID: <asp:TextBox ID="userIDText" runat="server"></asp:TextBox>
<br /><br />
Password: <asp:TextBox ID="passwordText" runat="server" TextMode="Password"></asp:TextBox>
<br /><br />
<asp:Button ID="submitBtn" runat="server" Text="Login" onclick="submitBtn_Click" />
public partial class UserLogin : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    public event EventHandler<LoginEventArgs> LoginEvent;
    public string UserID
    {
        get { return userIDText.Text; }
        set { userIDText.Text = value; }
    }

    protected void submitBtn_Click(object sender, EventArgs e)
    {
        LoginEventArgs args
            = new LoginEventArgs { IsAuthenticated = false };

        if (userIDText.Text == "admin" && passwordText.Text == "password")
        {
             args.IsAuthenticated = true;
        }
        if (LoginEvent != null)
        {
             LoginEvent(this, args);
        }
    }
}

– Page –

Be careful with “LoginEvent” property. You need to preceed with “On”.

<%@ Register src="UserLogin.ascx" tagname="UserLogin" tagprefix="uc1" %>
...
<uc1:UserLogin ID="UserLogin1" runat="server" UserID="admin" OnLoginEvent="loginBtn_Click" />
<br /><br />
<asp:Label ID="status" runat="server"></asp:Label>
protected void loginBtn_Click(object sender, LoginEventArgs e)
{
    if (e.IsAuthenticated)
    {
        status.Text = "You are logged in";
    }
    else
    {
        status.Text = "Sorry, please try it again";
    }
}

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s