R – ASP.NET Custom Controls

asp.netcustom-server-controls

How do you create a custom control (not an ASCX control) and, more importantly, use it in your project? I'd prefer not to create a separate project for it or compile it as a DLL

Best Answer

Server controls should be compiled into a DLL. There should be no reason to be afraid of having an additional assembly in your project, and it helps create good project organization.

ASP.NET Server controls are actually custom classes in an assembly. They do not have an "ascx" markup file associated to them.

To use a ASP.NET Server Control, you need to tell ASP.NET where to look for its class.

First, create a Class Library project and add it to your solution, I'll call mine "CustomControls.dll".

Once there, add a simple class to be your webcontrol:

public class Hello : System.Web.UI.WebControl
{
    public override Render(HtmlTextWriter writer)
    {
        writer.Write("Hello World");
        base.Render(writer);
    }
}

Build your project, and add it as a reference to your main web project.

Now, in the ASPX page that you want to use this control, you need to register it, so add this as the first line in the aspx AFTER the Page Directive:

<%@ Register TagPrefix="Example" Namespace="CustomControls" Assembly = "CustomControls" %>

Now, you should have a control named <Example:Hello> available to you. It might take it a minute to show up in intellisense.