Web Controls
There are two ways you can create your own controls in ASP.NET. The first is
known as custom controls, and is accomplished by creating a class deriving from
either System.Web.UI.Control or System.Web.UI.WebControls.WebControl. The
latter derives from the former, and adds additional UI properties to the class.
The other method is to create what is known as a user control, which is very
similiar to an ASP.NET page, but has an .ascx extension.
Web Custom Controls
As previsouly mention, System.Web.UI.Control and System.Web.UI.WebControl are
base classes for custom controls. For your control to be useful, you are
probably going to want to render some HTML to the browser. This is accomplished
by overriding the Control's Render method. An HtmlTextWriter parameter gives
you access to the output stream.
The following is a barebones custom control. Notice how the Render method is
using
System;
using
System.Web.UI;
using
System.Web.UI.WebControls;
namespace
WebCustomControl
{
 
public
class
FirstControl
:
Control
 
{
     protected
override
void
Render(
HtmlTextWriter
writer)
     {
     
writer.Write("Hello World");
     }
 
}
}
To use this control in a page, you need to register it with a Register
directive. The following ASP.NET page registers and uses the barebones control.
<%@ Register
TagPrefix="Custom"
Namespace="WebCustomControl"
Assembly="WebCustomControl"
%>
<html>
<body>
  <form
runat="server">
   Most
introductory
applications
output:
   <Custom:FirstControl
runat="server"
/>
  </form>
</body>
</html>
Web User Controls
Web User Controls are very much like ASP.NET page snippets. Like an ASPX page,
you can open them in design view, and add additional controls and HTML. They
are registered similiarly to Web Custom Controls. Using the Visual Studio.NET
IDE, you can drag an ascx control onto an ASP.NET page, and Visual Studio.NET
will take care of the registration and implementation tag for you. The
following is an example of a Web User Control.
<%@ Control Language="c#" AutoEventWireup="false"
Codebehind="header.ascx.cs" Inherits="DotnetCoders.Web.header" %>
Hello World!
Here is an HTML page utilizing the Web User Control.
<%@ Page
language="c#"
%>
<%@ Register TagPrefix="Custom"
TagName="FirstControl"
Src="~/header.ascx"
%>
<html>
<body>
  <form
runat="server">
   Most
introductory
applications
output:
   <Custom:FirstControl
runat="server"
/>
  </form>
</body>
</html>