views:

502

answers:

4

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

+1  A: 

Create the class for the control and build the solution. If everything goes well the control should now be available on the toolbox.

Sometimes the VS doesn't update the toolbox. If that happens add the Register directive to the page:

<%@ Register Assembly="NAME_OF_THE_ASSEMBLY" Namespace="NAMESPACE_OF_THE_CUSTOM_CONTROL" TagPrefix="cc1" %>

then just use the control on the page:

<cc1:mycustompanel id="MyCustomPanel1" runat="server"><asp:TextBox id="TextBox1" runat="server"></asp:TextBox></cc1:mycustompanel>
Bruno Shine
+6  A: 

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.

FlySwat
Thanks so much! Not only did this solve my problem but also helped me mature more as a developer.
Arthur Chaparyan
A: 

If you don't want a *.ascx file, you don't want a separate project, and you don't want a *.dll file, what do you think is left? The code has to live somewhere.

Joel Coehoorn
A: 

You mentioned that you wanted to avoid creating a separate project. As the other responses have indicated, it is far more common to simply create a new project to store your custom controls and reference it. It is possible, however, to register a control defined in the same project, using the regular syntax:

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

Where the "Assembly" is the assembly where both the control and the page is located. This works much easier if you are using a Web Application Project, rather than a Web Site.