New Document
ASP.NET - Server Controls

The basic building blocks of Microsoft ASP.NET Web Forms are Web controls (such as the Label, TextBox, and DataGrid. Web controls) placed on an ASP.NET Web Form by a declarative syntax not unlike traditional HTML elements. Underneath the covers, Web controls are actually classes within the Microsoft .NET Framework, and each Web control placed on an ASP.NET Web Form becomes an instance of its respective class when the Web Form is visited. This model provides two great benefits:

ASP.NET Web Form developers can easily add, move, and reposition Web controls on an ASP.NET page by simply editing the declarative syntax (or, with editors like Microsoft Visual Studio .NET, by dragging and dropping Web controls from the Toolbox onto the Design tab.)

Since Web controls are merely classes, the functionality of existing Web controls can be extended by creating new classes that derive from existing Web controls. Also, brand new Web controls can be formed by extending them from the base Web control class (System.Web.UI.WebControls.WebControl).

For information on using inheritance to extend the functionality of existing Web controls, check out my article Easily Adding Functionality to ASP.NET Server Controls or Marcie Robillard's Creating Custom Columns for the ASP.NET DataGrid. For information on building custom ASP.NET server controls from scratch, I highly recommend Nikhil Kothari and Vandana Datye's book, Developing Microsoft ASP.NET Server Controls and Components.

In this article we will examine how to build custom server controls that utilize templates. Templates allow for customization of a Web control's rendered output by providing a means for a page developer to specify HTML elements, Web controls, and databound statements. If you've worked with the ASP.NET data Web controls—the Repeater, DataList, or DataGrid—then you are already familiar with templates. The example below shows a DataList with its ItemTemplate and HeaderTemplate specified.

< asp:DataList runat="server" id="dlEmployees">
  < HeaderTemplate>
  < / HeaderTemplate>
  < ItemTemplate>
    Name: <%# DataBinder.Eval(Container.DataItem, "Name") %>
SSN: <%# DataBinder.Eval(Container.DataItem, "SSN") %>
< asp:LinkButton runat="server" Text="Delete" Command="Delete" /> < /ItemTemplate> < /asp:DataList>

As the above Web control syntax illustrates, templates can contain:

HTML markup-examples include the HeaderTemplate's contents and the text and
tags in the ItemTemplate

Web controls-the LinkButton in the ItemTemplate

Databound statements-the <%# ... %> syntax in the ItemTemplate.

The DataList is an example of a databound templated control. That is, page developers use the DataList by first setting its DataSource property to some enumerable data, such as a DataReader, DataSet, ArrayList, or any object that implements either IEnumerable or IListSouce interfaces. After setting the DataSource property, the page developer then calls the DataBind() method. The DataBind() method then enumerates through the specified DataSource and for each row creates a new "item" which contains the contents of the ItemTemplate, with the Web controls rendered as HTML and the databound statements resolved to the values in the current row being enumerated through in the DataSource.

Databound templated controls are a more complex, albeit more useful, form of templated controls. Templates can also be used with non-databound controls. For example, a control could use a template to allow for a high degree of customization of the HTML emitted by the control, as shown in the following example:

< skm:DisplayStats runat="server" TotalPostCount="15000">
  < StatsTemplate>
    There have been <%# Container.TotalPostCount %> posts...
  < /StatsTemplate>
< /skm:DisplayStats>
In this article we'll see how to add template support for non-databound custom ASP.NET server controls. Specifically, we'll look at creating a non-databound templated control, one that displays statistics for a fictional online messageboard site. In a future article, we'll examine a databound templated control that displays the latest entries to a blog. Adding template support is one of the more advanced features in server control building, so readers of this article should be familiar with the basics of creating custom server controls.

Controls are small building blocks of the graphical user interface, which includes text boxes, buttons, check boxes, list boxes, labels and numerous other tools, using which users can enter data, make selections and indicate their preferences.

Controls are also used for structural jobs, like validation, data access, security, creating master pages, data manipulation.

ASP.Net uses five types of web controls, which are:

  • HTML controls

  • HTML Server controls

  • ASP.Net Server controls

  • ASP.Net Ajax Server controls

  • User controls and custom controls

ASP.Net server controls are the primary controls used in ASP.Net. These controls again could be grouped into the following categories:

  • Validation controls - these are used to validate user input and work by running client-side script

  • Data source controls - these controls provides data binding to different data sources

  • Data view controls - these are various lists and tables, which can bind to data from data sources for display

  • Personalization controls - these are used for personalization of a page according to the user's preference, based on user information

  • Login and security controls - these controls provide user authentication

  • Master pages - these provides consistent layout and interface throughout the application

  • Navigation controls - these helps in navigation, for example, the menus, tree view etc.

  • Rich controls - these implements special features, for example, AdRotator control, FileUpload control, Calendar control etc.

The basic syntax for using server controls is:

<asp:controlType  ID ="ControlID" 
                     Property1=value1  [Property2=value2] />

However, visual studio has the following features, which helps in error free coding:

  • Dragging and dropping of controls in design view

  • IntelliSense feature that displays and auto-completes the properties

  • The properties window to set the property values directly

Properties of the Server Controls

The ASP.Net server controls with a visual aspect are derived from the WebControl class and inherit all the properties, events and methods of this class.

The WebControl class itself and some other server controls that are not visually rendered, e.g., the PlaceHolder control or XML control etc., are derived from the System.Web.UI.Control class.

ASP.Net server controls inherit all properties, events and methods of the WebControl and System.Web.UI.Control class.

The following table shows the inherited properties, which are common to all server controls:

AccessKey Pressing this key with the Alt key moves focus to the control
Attributes It's the collection of arbitrary attributes (for rendering only) that do not correspond to properties on the control.
BackColorBackground colour.
BindingContainerThe control that contains this control's data binding.
BorderColorBorder colour.
BorderStyleBorder style.
BorderWidthBorder width.
CausesValidationIndicates if it causes validation.
ChildControlCreatedIt indicates whether the server control's child controls have been created.
ClientIDControl ID for HTML markup.
ContextThe HttpContext object associated with the server control.
Controls Collection of all controls contained within the control
ControlStyleThe style of the Web server control.
CssClassCSS class
DataItemContainerGets a reference to the naming container if the naming container implements IDataItemContainer.
DataKeysContainerGets a reference to the naming container if the naming container implements IDataKeysControl.
DesignModeIt indicates whether the control is being used on a design surface.
DisabledCssClassGets or sets the CSS class to apply to the rendered HTML element when the control is disabled.
EnabledIndicates whether the control is grayed out
EnableThemingIndicates whether theming applies to the control.
EnableViewStateIndicates whether the view state of the control is maintained.
Events Gets a list of event handler delegates for the control.
FontFont .
ForecolorForeground colour.
HasAttributesIndicates whether the control has attributes set.
HasChildViewStateindicates whether the current server control's child controls have any saved view-state settings.
Height Height in pixels or %.
IDIdentifier for the control.
IsChildControlStateClearedIndicates whether controls contained within this control have control state.
IsEnabledGets a value indicating whether the control is enabled
IsTrackingViewStateIt indicates whether the server control is saving changes to its view state.
IsViewStateEnabledIt indicates whether view state is enabled for this control.
LoadViewStateByIdIt indicates whether the control participates in loading its view state by ID instead of index.
PagePage containing the control.
ParentParent control.
RenderingCompatibilityIt specifies the ASP.NET version that rendered HTML will be compatible with.
SiteThe container that hosts the current control when rendered on a design surface.
SkinIDGets or sets the skin to apply to the control. (
StyleGets a collection of text attributes that will be rendered as a style attribute on the outer tag of the Web server control.
TabIndexGets or sets the tab index of the Web server control.
TagKeyGets the HtmlTextWriterTag value that corresponds to this Web server control.
TagNameGets the name of the control tag.
TemplateControlThe template that contains this control.
TemplateSourceDirectoryGets the virtual directory of the Page or control containing this control.
ToolTipGets or sets the text displayed when the mouse pointer hovers over the Web server control.
UniqueIDUnique identifier
ViewStateGets a dictionary of state information that allows you to save and restore the view state of a server control across multiple requests for the same page.
ViewStateIgnoreCaseIt indicates whether the StateBag object is case-insensitive.
ViewStateMode Gets or sets the view-state mode of this control.
VisibleIt indicates whether a server control is visible.
WidthGets or sets the width of the Web server control.

Methods of the Server Controls

The following table provides the methods of the server controls:

AddAttributesToRenderAdds HTML attributes and styles that need to be rendered to the specified HtmlTextWriterTag.
AddedControlCalled after a child control is added to the Controls collection of the Control object.
AddParsedSubObjectNotifies the server control that an element, either XML or HTML, was parsed, and adds the element to the server control's control collection.
ApplyStyleSheetSkinApplies the style properties defined in the page style sheet to the control.
ClearCachedClientIDInfrastructure. Sets the cached ClientID value to null.
ClearChildControlStateDeletes the control-state information for the server control's child controls.
ClearChildStateDeletes the view-state and control-state information for all the server control's child controls.
ClearChildViewStateDeletes the view-state information for all the server control's child controls.
CreateChildControlsUsed in creating child controls.
CreateControlCollectionCreates a new ControlCollection object to hold the child controls.
CreateControlStyleCreates the style object that is used to implement all style related properties.
DataBindBinds a data source to the server control and all its child controls.
DataBind(Boolean)Binds a data source to the server control and all its child controls with an option to raise the DataBinding event.
DataBindChildrenBinds a data source to the server control's child controls.
DisposeEnables a server control to perform final clean up before it is released from memory.
EnsureChildControlsDetermines whether the server control contains child controls. If it does not, it creates child controls.
EnsureIDCreates an identifier for controls that do not have an identifier.
Equals(Object)Determines whether the specified Object is equal to the current Object.
FinalizeAllows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
FindControl(String)Searches the current naming container for a server control with the specified id parameter.
FindControl(String, Int32)Searches the current naming container for a server control with the specified id and an integer
FocusSets input focus to a control.
GetDesignModeStateGets design-time data for a control.
GetTypeGets the Type of the current instance.
GetUniqueIDRelativeToReturns the prefixed portion of the UniqueID property of the specified control.
HasControlsDetermines if the server control contains any child controls.
HasEventsIndicates whether events are registered for the control or any child controls.
IsLiteralContentDetermines if the server control holds only literal content.
LoadControlStateRestores control-state information.
LoadViewStateRestores view-state information.
MapPathSecureRetrieves the physical path that a virtual path, either absolute or relative, maps to.
MemberwiseCloneCreates a shallow copy of the current object.
MergeStyleCopies any nonblank elements of the specified style to the Web control, but will not overwrite any existing style elements of the control.
OnBubbleEventDetermines whether the event for the server control is passed up the page's UI server control hierarchy.
OnDataBindingRaises the data binding event.
OnInitRaises the Init event.
OnLoadRaises the Load event.
OnPreRenderRaises the PreRender event.
OnUnloadRaises the Unload event.
OpenFileGets a Stream used to read a file
RemovedControlCalled after a child control is removed from the Controls collection of the Control object.
RenderRenders the control to the specified HTML writer.
RenderBeginTagRenders the HTML opening tag of the control to the specified writer.
RenderChildrenOutputs the content of a server control's children to a provided HtmlTextWriter object, which writes the content to be rendered on the client.
RenderContentsRenders the contents of the control to the specified writer.
RenderControl(HtmlTextWriter)Outputs server control content to a provided HtmlTextWriter object and stores tracing information about the control if tracing is enabled.
RenderEndTagRenders the HTML closing tag of the control into the specified writer.
ResolveAdapterGets the control adapter responsible for rendering the specified control.
SaveControlStateSaves any server control state changes that have occurred since the time the page was posted back to the server.
SaveViewStateSaves any state that was modified after the TrackViewState method was invoked.
SetDesignModeStateSets design-time data for a control.
ToStringReturns a String that represents the current object.
TrackViewStateCauses the control to track changes to its view state so they can be stored in the object's view state property.


Let us look at a particular server control - a tree view control. A Tree view control comes under navigation controls. Other Navigation controls are: Menu control and SiteMapPath control.

Add a tree view control on the page. Select Edit Nodes... from the tasks. Edit each of the nodes using the Tree view node editor:

ASP.NET Edit Nodes

Once you have created the nodes, it looks like the following in design view:

ASP.NET Edit Nodes2

The AutoFormat... task allows you to format the tree view:

ASP.NET AutoFormat

Add a label control and a text box control on the page and name them lblmessage and txtmessage respectively.

Write few lines of code to ensure that when a particular node is selected, the label control displays the node text and the text box displays all child nodes under it, if any. The code behind file should look like this:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace eventdemo
  public partial class treeviewdemo : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
      txtmessage.Text = " "; 
   protected void TreeView1_SelectedNodeChanged(object sender, 
                                                EventArgs e)
    txtmessage.Text = " "; 
    lblmessage.Text = "Selected node changed to: " + 
    TreeNodeCollection childnodes = 
    if(childnodes != null)
      txtmessage.Text = " ";
      foreach (TreeNode t in childnodes)
         txtmessage.Text += t.Value;

Run the page to see the effects. You will be able to expand and control the nodes.

ASP.NET Control Nodes

Region-based editing. Regions are editable areas in the design-time view of a control. This feature offers WYSIWYG editing of a control's contents at design time.

Action lists. Action lists are menus of tasks that the page developer of a control can use in the design-time UI. For example, the design-time view of your control could provide a menu of available tasks, including a task to format the control automatically.

Data source and data-bound designers. Data source control designers allow the page developer to configure data source controls. Data-bound control designers allow the page developer to configure data-bound controls. Features are available to implement cross communication between the data source and data-bound designers. For an example of a data source control designer, see DataSourceDesigner. For an example of a data-bound control designer, see HierarchicalDataBoundControlDesigner.

Simplified template editing. The model for creating a UI for design-time editing of templated controls (such as GridView) has been drastically simplified and modified so that the control developer can choose to perform his or her own template editing with regions. For an example, see Templated Server Control Example.

Simplified object model. The object model for working with design-time rendering is simplified, so that the only significant issue a developer has to be concerned with is producing design-time HTML. Several new base classes provide access to the simplified object model: ControlDesigner, ContainerControlDesigner, and CompositeControlDesigner.

Subscription to host services. A control designer can subscribe to and use various services provided by the host environment. For example, a control designer can use Visual Studio 2005 services to provide access to data, provide access to configuration, add controls to a page programmatically at design time, handle click events in the designer, paint on the design surface, and access other services such as designer-state.

Previous                                                                                                                                                       Next

Back to Top