Professional Documents
Culture Documents
User control
1) Reusability web page
2) We can’t add to toolbox
3) Just drag and drop from solution explorer to page (aspx)
4) U can register user control to. Aspx page by Register tag
5) A separate copy of the control is required in each application
6) Good for static layout
7) Easier to create
8)Not complied into DLL
9) Here page (user page) can be converted as control then
We can use as control in aspx
Custom controls
1) Reusability of control (or extend functionalities of existing control)
2) We can add toolbox
3) Just drag and drop from toolbox
4) U can register user control to. Aspx page by Register tag
5) A single copy of the control is required in each application
6) Good for dynamics layout
7) Hard to create
8) Compiled in to dll
User controls are custom, reusable controls, and they use the same techniques that are employed by HTML and Web server
controls. They offer an easy way to partition and reuse common user interfaces across ASP.NET Web applications. They use
the same Web Forms programming model on which a Web Forms page works.
The syntax you use to create a user control is similar to the syntax you use to create a Web Forms page (.aspx). The only
difference is that a user control does not include the <html>, <body>, and <form> elements since a Web Forms page hosts
Open a text or HTML editor, and create a server-side code block exposing all the properties, methods, and events.
Create a new Web Forms page (.aspx) in Microsoft Visual Studio .NET 2002, Microsoft Visual Studio .NET 2003, Microsoft
Declare the @ Register directive. For example, use the following code.
To use the user control in the Web Forms page, use the following code after the @ Register directive.
<html>
<body>
<form runat="server">
<UC:TestControl id="Test1" runat="server"/>
</form>
</body>
</html>
How to create an instance of a user control programmatically in the code behind file of a Web Forms page
The previous example instantiated a user control declaratively in a Web Forms page using the @ Register directive.
However, you can instantiate a user control dynamically and add it to the page. Here are the steps for doing that:
Navigate to the code behind file generated for this Web Forms page.
In the Page_Load event of the Page class, write the following code.
// Load the control by calling LoadControl on the page class.
Control c1 = LoadControl("test.ascx");
// Add the loaded control in the page controls collection.
Page.Controls.Add(c1);
Note You can add a user control dynamically at certain events of the page life cycle.
The page parser parses the .ascx file specified in the Src attribute in the @ Register directive and generates a class that
If you are using Visual Studio, then at design time only, Visual Studio creates a code behind file for the user control, and the
Finally, the class for the user control, which is generated through the process of dynamic code generation and compilation,
includes the code for the code behind file (.ascx.cs) as well as the code written inside the .ascx file.
What are custom controls?
Custom controls are compiled code components that execute on the server, expose the object model, and render markup
text, such as HTML or XML, as a normal Web Form or user control does.
To write a custom control, you should directly or indirectly derive the new class from the System.Web.UI.Control class or
You should derive from System.Web.UI.Control if you want the control to render nonvisual elements. For example,
You should derive from System.Web.UI.WebControls.WebControl if you want the control to render HTML that generates
If you want to change the functionality of existing controls, such as a button or label, you can directly derive the new class
with these existing classes and can change their default behavior.
In brief, the Control class provides the basic functionality by which you can place it in the control tree for a Page class. The
WebControl class adds the functionality to the base Control class for displaying visual content on the client computer. For
example, you can use the WebControl class to control the look and styles through properties like font, color, and height.
How to create and use a simple custom control that extends from System.Web.UI.Control using Visual
Studio
Create a class library project, and give it a name, for example, CustomServerControlsLib.
Check whether the following namespaces are included in the SimpleServerControl.cs file.
System
System.Collections
System.ComponentModel
System.Data
System.Web
System.Web.SessionState
System.Web.UI
System.Web.UI.WebControls
Override the Render method to write the output to the output stream.
HtmlTextWriter class outputs the specified text to the HTTP response stream and is the same as the Response.Write
method.
Compile the class library project. It will generate the DLL output.
Add a Web Forms page where the custom control can be used.
Add a reference to the class library in the references section of the ASP.NET project.
To instantiate or use the custom control on the Web Forms page, add the following line of code in the <form> tags.
Run the Web Forms page, and you will see the output from the custom control.
If you are not using Visual Studio, you need to perform the following steps:
Create a file named SimpleServerControl.cs, and write the code as given in steps 1 through 14.
c:\windows (winnt)\Microsoft.Net\Framework\v1.1.4322
SimpleServerControl.cs
To run the custom control on the Web Forms page, do the following:
Start Microsoft Internet Information Services (IIS) Manager, and mark the new directory as the virtual rootdirectory.
Place the sample Web Forms page that you created in the previous steps inside the new directory.
Now that you have built a simple custom control, let's look at how to expose properties and apply design-time attributes on
I will build on the previous example and introduce one or more properties that can be configured while using the custom
To use the custom control on the Web Forms page, add the new property to the control declaration.
<CC:SimpleServerControl id="ctlSimpleControl" NoOfTimes="5"
runat="server"></CC:SimpleServerControl>
Running the page will display the message "Hello world" from the custom control as many times as specified in the
The custom control that you built in the previous example works as expected. However, if you want to use that control in
Visual Studio, you may want the NoOfTimes property to be automatically highlighted in the Properties window whenever the
To make this happen, you need to provide the metadata information to Visual Studio, which you can do by using a feature in
Visual Studio called attributes. Attributes can define a class, a method, a property, or a field. When Visual Studio loads the
custom control's class, it checks for any attributes defined at the class, method, property, or field level and changes the
There is one more tag called TagPrefixAttrbute. It is an assembly-level attribute that provides a prefix to a tag when you
drag the control from the Toolbox to the designer. Otherwise, the designer generates a prefix such as "cc1" by default.
TagPrefixAttrbute is not directly applied to the control class. To apply TagPrefixAttrbute, open AssemblyInfo.cs, include
Note If you want to build the source using the command line, you need to create the AssemblyInfo.cs file, place the file in
the directory that contains all the source files, and run the following command to build the control:
What are the basic differences between user controls and custom controls?
Now that you have a basic idea of what user controls and custom controls are and how to create them, let's take a quick look
Deployment Designed for single-application scenarios Designed so that it can be used by more than one application
Deployed in the source form (.ascx) along with Deployed either in the application's Bin directory or in the global
the source code of the application assembly cache
If the same control needs to be used in more Distributed easily and without problems associated with
than one application, it introduces redundancy redundancy and maintenance
and maintenance problems
Creation Creation is similar to the way Web Forms pages Writing involves lots of code because there is no designer
are created; well-suited for rapid application support
development (RAD)
Content A much better choice when you need static More suited for when an application requires dynamic content to
content within a fixed layout, for example, be displayed; can be reused across an application, for example,
when you make headers and footers for a data bound table control with dynamic rows
Design Writing doesn't require much application Writing from scratch requires a good understanding of the
designing because they are authored at design control's life cycle and the order in which events execute, which
time and mostly contain static data is normally taken care of in user controls
Advanced topics
Next, let's take a look at a few of the advanced features that you may use while developing custom controls.
State management
Web applications are built on HTTP, which is stateless. A page and its child controls are created on every request and are
disposed of after the request is over. To maintain state in classic ASP programming, you use session and application objects.
But for that, you need to do lots of coding. To avoid this, ASP.NET provides a mechanism known as view state for
maintaining state across several requests. To learn more about state management and view state, visit the following MSDN
Web sites:
ViewStateExample.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text;
namespace ServerControlLib
{
/// <summary>
/// When a page framework reloads this control after postback, it
/// will restore the values which are in view state.
/// This control can easily perform state management without
/// implementing our own logic for maintaining the state.
/// </summary>
public class ViewStateExample : WebControl
{
// Text to be displayed in Text box control.
private string _text;
// This property needs to be populated before every postback in order to
// retain its value.
public string Text
{get { return (_text == null) ? "_text property is empty" : _text; }
set { _text = value; }
}
// This property needs to be filled once and should be
// available on the successive postbacks.
public string TextInViewState
{ get
{
object o = ViewState["TextInViewState"];
return (o == null) ? "View state is empty" : (string)o;
}
set { ViewState["TextInViewState"] = value; }
}
/* Over-ridden method on WebControl base class which displays both of the
property values i.e. one stored in view state and other which is not saved in view
state. */
protected override void RenderContents(HtmlTextWriter writer)
{ writer.Write("Text Without View State = ");
writer.Write(Text);writer.Write("<hr><br>");
writer.Write("Text In View State = ");
writer.Write(TextInViewState);
} }}
ViewStateExampleDemo.aspx
<%@ Page Language="C#" %>
<%@ Register TagPrefix="CC" Namespace="ServerControlLib" Assembly = "ServerControlLib" %>
<html>
<head>
<script runat="server">
void button1_Click(object sender, EventArgs e)
{ Control1.Text = textbox1.Text;Control1.TextInViewState = textbox2.Text;
}
</script>
</head>
<body>
<form runat="server" ID="Form1"><br> Property Value Without View State: <asp:TextBox
id="textbox1" runat="server" />
<br> Property Value with View State: <asp:TextBox id="textbox2" runat="server" />
<asp:Button text="Cause Postback" onClick="button1_Click" id="button1" Runat="server"/>
Output from the ViewStateExample Control :<CC:ViewStateExample id="Control1"
runat="server"/>
</form>
</body>
</html>
Rendering
In this section, I'll briefly describe what methods you should override when you derive a custom control from either the
Every page has a control tree that represents a collection of all the child controls for that page. To render the control tree, an
object of the HtmlTextWriter class is created that contains the HTML to be rendered on the client computer. That object is
passed to the RenderControl method. In turn, the RenderControl method invokes the Render method. Then, the Render
method calls the RenderChildren method on each child control, making a recursive loop until the end of the collection is
The following code example shows the Render method for the custom control.
protected override void Render(HtmlTextWriter writer)
{ RenderBeginTag(writer); RenderContents(writer); RenderEndTag(writer);}
You don't need to override the Render method for the WebControl class. If you want to render contents within the
WebControl class, you need to override the RenderContents method. However, if you still want to override the Render
method, you must override the RenderBeginTag method as well as the RenderEndTag method in the specific order that is