Creating custom controls in ASP.NET

In this we see what is custom control in ASP.NET. how can we create it and how we add it in our website and use it in ASP.NET.

Custom controls in ASP.NET are the controls that is designed by user using source code. It can be shared across applications.
It can be created in 3 three different ways:

a.Deriving a custom control from web controls.
b.Making a composite custom control by combining 2 or more existing controls
c.Using Existing Controls.

I have discussed here "using web controls"

First add the namespace System.Web.UI.WebControls
a. Using Web Controls.

1. File -> new project -> new server control

Their is a code in that page replace it by following code:

namespace SimpleCustomControl
[ToolboxData("<{0}:ServerControl1 runat=server>")]
public class ServerControl1 : WebControl
public string Text
String s = (String)ViewState["Text"];
return ((s == null) ? "[" + this.ID + "]" : s);

ViewState["Text"] = value;

public int size
return (Convert.ToInt32(ViewState["Size"]));
ViewState["Size"] = value;

protected override void RenderContents(HtmlTextWriter output)
output.Write("" + Text + "");


Text and fontsize is entered by user in the website where we add this control to the website's webpage.

In the first line [DefaultProperty("Text")]-> by defalut every controls Text property is selected. We can change it like we can use ID also.
[ToolboxData("<{0}:ServerControl1 runat=server>")] -> {0} is the tagprefix and ServerControl1 is the class name.
public class ServerControl1 : WebControl -> ServerControl1 is TagName which can be changed

2. Now create a new website and add the dll of the above servercontrol to this website.
from select solution explorer -> add reference -> select serverconrolproject name -> bin -> debug -> select dll file

3. Register the servercontrol in your website's webpage:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="SimpleCustomControl" Namespace="SimpleCustomControl" TagPrefix="ASP" %>

Assembly="SimpleCustomControl" Namespace="SimpleCustomControl" -> it is the servercontrols project name
tagprefix -> it is taken by us whatever we want.

4. Add the server control in the webpage anywhere.

by adding following code:

<ASP:ServerControl1 ID="S1" runat="server" size="5" Text="My Server Control" />

* Here size and text is necessary as we have used it in our servercontrol code.


No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: