Working with ASP.NET Master Pages Programmatically

Wednesday, July 22, 2009

You can perform a number of common tasks programmatically with master pages, including the following:

  • Accessing members that are defined on the master page, which can consist of public properties and methods or controls.
  • Attaching master pages to a content page dynamically.

 Accessing Members on the Master Page

To provide access to members of the master page, the Page class exposes a Master property. To access members of a specific master page from a content page, you can create a strongly typed reference to the master page by creating a @ MasterType directive. The directive allows you to point to a specific master page. When the page creates its Master property, the property is typed to the referenced master page.

For example, you might have a master page named MasterPage.master that is the class name MasterPage_master. You might create @ Page and @ MasterType directives that look like the following:

<%@ Page  masterPageFile="~/MasterPage.master"%>

<%@ MasterType  virtualPath="~/MasterPage.master"%>

When you use a @ MasterType directive, such as the one in the example, you can reference members on the master page as in the following example:

Visual Basic


Copy Code

CompanyName.Text = Master.CompanyName

C#


Copy Code

CompanyName.Text = Master.CompanyName;

The Master property of the page is already typed to MasterPage_master.

Getting the Values of Controls on the Master Page

At run time, the master page is merged with the content page, so the controls on the master page are accessible to content page code. (If the master page contains controls in a ContentPlaceHolder control, those controls are not accessible if overridden by a Content control from the content page.) The controls are not directly accessible as master-page members because they are protected. However, you can use the FindControl method to locate specific controls on the master page. If the control that you want to access is inside a ContentPlaceHolder control on the master page, you must first get a reference to the ContentPlaceHolder control, and then call its FindControl method to get a reference to the control.

The following example shows how you can get a reference to controls on the master page. One of the controls being referenced is in a ContentPlaceHolder control and the other is not.

Visual Basic


Copy Code

' Gets a reference to a TextBox control inside a ContentPlaceHolder

Dim mpContentPlaceHolder As ContentPlaceHolder

Dim mpTextBox As TextBox

mpContentPlaceHolder = _

CType(Master.FindControl("ContentPlaceHolder1"), _

ContentPlaceHolder)

If
Not mpContentPlaceHolder Is
Nothing
Then

mpTextBox = CType(mpContentPlaceHolder.FindControl("TextBox1"), _

TextBox)


If
Not mpTextBox Is
Nothing
Then

mpTextBox.Text = "TextBox found!"


End
If

End
If


 

' Gets a reference to a Label control that is not in a

' ContentPlaceHolder control

Dim mpLabel As Label

mpLabel = CType(Master.FindControl("masterPageLabel"), Label)

If
Not mpLabel Is
Nothing
Then

Label1.Text = "Master page label = " + mpLabel.Text

End
If

C#


Copy Code

// Gets a reference to a TextBox control inside a ContentPlaceHolder

ContentPlaceHolder mpContentPlaceHolder;

TextBox mpTextBox;

mpContentPlaceHolder =

(ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");

if(mpContentPlaceHolder != null)

{

mpTextBox = (TextBox) mpContentPlaceHolder.FindControl("TextBox1");


if(mpTextBox != null)

{

mpTextBox.Text = "TextBox found!";

}

}


 

// Gets a reference to a Label control that is not in a

// ContentPlaceHolder control

Label mpLabel = (Label) Master.FindControl("masterPageLabel");

if(mpLabel != null)

{

Label1.Text = "Master page label = " + mpLabel.Text;

}


 

You can access the contents of the master page's ContentPlaceHolder controls by using the FindControl method, as shown above. If the ContentPlaceHolder control has been merged with content from a Content control, the ContentPlaceHolder control will not contain its default content. Instead, it will contain the text and controls that are defined in the content page.

 Attaching Master Pages Dynamically

In addition to specifying a master page declaratively (in the @ Page directive or in the configuration file), you can attach a master page dynamically to a content page. Because the master page and content page are merged during the initialization stage of page processing, a master page must be assigned before then. Typically, you assign a master page dynamically during the PreInit stage, as in the following example:

Visual Basic


Copy Code

Sub Page_PreInit(ByVal sender As Object, ByVal e As EventArgs) _

Handles Me.PreInit

Me.MasterPageFile = "~/NewMaster.master"

End Sub

C#


Copy Code

void Page_PreInit(Object sender, EventArgs e)

{

this.MasterPageFile = "~/NewMaster.master";

}

Strong Typing for Dynamic Master Pages

If the content page assigns a strong type to the master page by using a @ MasterType directive, the type must apply to any master page that you assign dynamically. If you intend to select a master page dynamically, it is recommended that you create a base class from which your master pages derive. The base master-page class can then define the properties and methods that the master pages have in common. In the content page, when you assign a strong type to the master page by using a @ MasterType directive, you can assign it to the base class instead of to an individual master page.

The following examples show how to create a base master-page type that can be used by multiple master pages. The examples consist of a base type that is derived from the MasterPage control, two master pages that inherit from the base type, and a content page that allows users to select a master page dynamically by using a query string (?color=green). The base master type defines a property named MyTitle. One of the master pages overrides the MyTitle property, and the other one does not. The content page displays the MyTitle property as the page's title. The title of the page will therefore vary depending on which master page has been selected.

This is the base master-page type. It belongs in the App_Code directory.

Visual Basic


Copy Code

Public
Class BaseMaster


Inherits MasterPage


Public
Overridable
ReadOnly
Property MyTitle() As
String


Get


Return
"BaseMaster Title"


End
Get


End
Property

End
Class

C#


Copy Code

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

public
class BaseMaster : System.Web.UI.MasterPage

{


public virtual String MyTitle

{


get { return
"BaseMaster Title"; }

}

}

This is the first master page, which displays a blue background. Notice that the Inherits attribute in the @ Master directive references the base type.

Visual Basic


Copy Code

<%@ Master Language="VB"
Inherits="BaseMaster"

ClassName="MasterBlue" %>

<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.1//EN"


"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<script runat="server">


' No property here that overrrides the MyTitle property of the base master.

</script>


 

<html >

<head runat="server">

<title>No title</title>

</head>

<body>

<form id="form1" runat="server">

<div style="background-color:LightBlue">

<asp:contentplaceholder id="ContentPlaceHolder1"

runat="server">

Content from MasterBlue.

</asp:contentplaceholder>

</div>

</form>

</body>

</html>

C#


Copy Code

<%@ Master Language="C#" Inherits="BaseMaster"

ClassName="MasterBlue" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"


"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<script runat="server">


// No property here that overrrides the MyTitle property of the base master.

</script>


 

<html >

<head id="Head1" runat="server">

<title>No title</title>

</head>

<body>

<form id="form1" runat="server">

<div style="background-color:LightBlue">

<asp:contentplaceholder id="ContentPlaceHolder1"

runat="server">

Content from MasterBlue.

</asp:contentplaceholder>

</div>

</form>

</body>

</html>

This is the second master page. It is the same as the first master page, except that it displays a green background, and it overrides the MyTitle property that is defined in the base type.

Visual Basic


Copy Code

<%@ Master Language="VB"
Inherits="BaseMaster"

ClassName="MasterGreen" %>

<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.1//EN"


"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">


 

<script runat="server">


Public
Overrides
ReadOnly
Property MyTitle() As
String


Get


Return
"MasterGreen Title"


End
Get


End
Property

</script>


 

<html >

<head runat="server">

<title>No title</title>

</head>

<body>

<form id="form1" runat="server">

<div style="background-color:LightGreen">

<asp:contentplaceholder id="ContentPlaceHolder1" runat="server">

Content from MasterGreen.

</asp:contentplaceholder>

</div>

</form>

</body>

</html>

C#


Copy Code

<%@ Master Language="C#" Inherits="BaseMaster"

ClassName="MasterGreen" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"


"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">


 

<script runat="server">


public override String MyTitle

{


get { return
"MasterGreen Title"; }

}

</script>


 

<html >

<head id="Head1" runat="server">

<title>No title</title>

</head>

<body>

<form id="form1" runat="server">

<div style="background-color:LightGreen">

<asp:contentplaceholder id="ContentPlaceHolder1"

runat="server">

Content from MasterGreen.

</asp:contentplaceholder>

</div>

</form>

</body>

</html>

This is the content page, which allows users to select a master page based on a query string provided with the request. The @ MasterType directive, which assigns a strong type to the page's Master property, references the base type.

Visual Basic


Copy Code

<%@ Page Language="VB" Title="Content Page" MasterPageFile="~/MasterBlue.master"%>

<%@ MasterType TypeName="BaseMaster" %>

<script runat="server">


 


Protected
Sub Page_PreInit(ByVal sender As
Object,


ByVal e As System.EventArgs)


Me.MasterPageFile = "MasterBlue.master"


If Request.QueryString("color") = "green"
Then


Me.MasterPageFile = "MasterGreen.master"


End
If


Me.Title = Master.MyTitle


End
Sub

</script>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

Content from Content page.

</asp:Content>

C#


Copy Code

<%@ Page Language="C#" Title="Content Page" MasterPageFile="~/MasterBlue.master"%>

<%@ MasterType TypeName="BaseMaster" %>

<script runat="server">


protected
void Page_PreInit(Object sender, EventArgs e)

{


this.MasterPageFile = "MasterBlue.master";


if(Request.QueryString["color"] == "green")

{


this.MasterPageFile = "MasterGreen.master";

}


this.Title = Master.MyTitle;

}

</script>


 

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1"

Runat="Server">

Content from Content page.

</asp:Content>


 


 

In this fashion can create Master pages and use them in your cms


 

For more help

usamawahabkhan@gmail.com


 

Css Tutorials

Styles Solved a Big Problem

The original HTML was never intended to contain tags for formatting a document. HTML tags were intended to define the content of a document, like:


 

<p>This is a paragraph.</p>


 

<h1>This is a heading</h1>


 

When tags like <font> and color attributes were added to the HTML 3.2 specification, it started a nightmare for web developers. Development of large web sites where fonts and color information had to be added to every single Web page, became a long, expensive and unduly painful process.


 

To solve this problem, the World Wide Web Consortium (W3C) - responsible for standardizing HTML - created CSS in addition to HTML 4.0.


 

With HTML 4.0, all formatting can be removed from the HTML document and stored in a separate CSS file.


 

All browsers support CSS today.


 


 

--------------------------------------------------------------------------------


 

CSS Saves a Lot of Work

Styles sheets define HOW HTML elements are to be displayed.


 

Styles are normally saved in external .css files. External style sheets enable you to change the appearance and layout of all the pages in a Web site, just by editing one single CSS document!


 


 

--------------------------------------------------------------------------------


 

Multiple Styles Will Cascade into One

Style sheets allow style information to be specified in many ways.


 

Styles can be specified:


 

inside an HTML element

inside the head section of an HTML page

in an external CSS file

Tip: Even multiple external style sheets can be referenced inside a single HTML document.


 

Cascading order - What style will be used when there is more than one style specified for an HTML element?

Generally speaking we can say that all the styles will "cascade" into a new "virtual" style sheet by the following rules, where number four has the highest priority:


 

Browser default

External style sheet

Internal style sheet (in the head section)

Inline style (inside an HTML element)

So, an inline style (inside an HTML element) has the highest priority, which means that it will override a style defined inside the <head> tag, or in an external style sheet, or in a browser (a default value).


 

If the link to the external style sheet is placed after the internal style sheet in HTML <head>, the external style sheet will override the internal style sheet!


 

Syntax

The CSS syntax is made up of three parts: a selector, a property and a value:


 

selector {property:value}


 

The selector is normally the HTML element/tag you wish to define, the property is the attribute you wish to change, and each property can take a value. The property and value are separated by a colon, and surrounded by curly braces:


 

body {color:black}


 

Note: If the value is multiple words, put quotes around the value:


 

p {font-family:"sans serif"}


 

Note: If you want to specify more than one property, you must separate each property with a semicolon. The example below shows how to define a center aligned paragraph, with a red text color:


 

p {text-align:center;color:red}


 

To make the style definitions more readable, you can describe one property on each line, like this:


 

p

{

text-align:center;

color:black;

font-family:arial

}


 


 

--------------------------------------------------------------------------------


 

Grouping

You can group selectors. Separate each selector with a comma. In the example below we have grouped all the header elements. All header elements will be displayed in green text color:


 

h1,h2,h3,h4,h5,h6

{

color:green

}


 


 

--------------------------------------------------------------------------------


 

The class Selector

With the class selector you can define different styles for the same type of HTML element.


 

Say that you would like to have two types of paragraphs in your document: one right-aligned paragraph, and one center-aligned paragraph. Here is how you can do it with styles:


 

p.right {text-align:right}

p.center {text-align:center}


 

You have to use the class attribute in your HTML document:


 

<p class="right">This paragraph will be right-aligned.</p>

<p class="center">This paragraph will be center-aligned.</p>


 

Note: To apply more than one class per given element, the syntax is:


 

<p class="center bold">This is a paragraph.</p>


 

The paragraph above will be styled by the class "center" AND the class "bold".


 

You can also omit the tag name in the selector to define a style that will be used by all HTML elements that have a certain class. In the example below, all HTML elements with class="center" will be center-aligned:


 

.center {text-align:center}


 

In the code below both the h1 element and the p element have class="center". This means that both elements will follow the rules in the ".center" selector:


 

<h1 class="center">This heading will be center-aligned</h1>

<p class="center">This paragraph will also be center-aligned.</p>


 

Do NOT start a class name with a number! It will not work in Mozilla/Firefox.


 


 

--------------------------------------------------------------------------------


 

Add Styles to Elements with Particular Attributes

You can also apply styles to HTML elements with particular attributes.


 

The style rule below will match all input elements that have a type attribute with a value of "text":


 

input[type="text"] {background-color:blue}


 


 

--------------------------------------------------------------------------------


 

The id Selector

You can also define styles for HTML elements with the id selector. The id selector is defined as a #.


 

The style rule below will match the element that has an id attribute with a value of "green":


 

#green {color:green}


 

The style rule below will match the p element that has an id with a value of "para1":


 

p#para1

{

text-align:center;

color:red

}


 

Do NOT start an ID name with a number! It will not work in Mozilla/Firefox.


 


 

--------------------------------------------------------------------------------


 

CSS Comments

Comments are used to explain your code, and may help you when you edit the source code at a later date. A comment will be ignored by browsers. A CSS comment begins with "/*", and ends with "*/", like this:


 

/*This is a comment*/

p

{

text-align:center;

/*This is another comment*/

color:black;

font-family:arial

}


 


 

For more help

usamawahabkhan@gmail.com

Visual Studio 2008 Css Support

One of the big features that web developers will quickly discover with VS 2008 is its dramatically improved HTML designer, and the rich CSS support it brings. 

VS 2008 now uses the same web designer that ships with Microsoft's new Expression Web product.  In addition to providing lots of new functionality, you'll also find that this web designer is much faster than the VS 2005 version (which was based on a much older code base).

Below is a quick tour of some of the new web designer features that you'll be able to take advantage of with both VS 2008 as well as the free Visual Web Developer 2008 Express:

Split View Editing

In addition to supporting both source-view and design-view, VS 2008 adds support for a new "split-view" mode when working on pages.  This allows you to see both the HTML source and the Design View at the same-time, and easily have any changes you make in one view be updated in the other:

 

CSS Style Manager

VS 2008 supports a new tool window inside the IDE called "Manage Styles".  This shows all of the CSS stylesheets, and their corresponding rules, for the page you are currently editing.  It can be used both when you are in design-view, as well as when you are in source view on a page:


A circle around a CSS rule in the manage styles window indicates that particular rule is in use within the current document.  Using the mouse to hover over the rule allows you to quickly see the CSS rule values:


You can then either right-click on a CSS rule and select "Modify Style" to bring up a graphical CSS rules editor, or you can double click on the rule in the manage styles window to automatically open the stylesheet file and jump immediately to the CSS source definition to edit (with full intellisense):


For even more tips/tricks about how to best use the "Manage Styles" tool window please read this blog post.

CSS Properties Window

One of the other cool new CSS features that is also supported in both design and source view is the new CSS Properties Window:


When you select an HTML element or ASP.NET server control, the CSS property window will show you all of the CSS settings currently applied to it. You can also change any of the values using the CSS property grid. The "target rule" drop-down in the style toolbar allows you to determine under what rule the settings are applied (read this blog post to learn more about the style toolbar and target rule dropdown). 

If, like me, you sometimes struggle with large CSS stylesheets and find yourself shouting "why the $!#@ is it looking like that?", you'll find the "summary" view of the CSS Properties window really useful (just click the summary button at the top of the CSS properties pane).  When you press this button it enables a filtering mode that shows you the full inheritance set of CSS rules for the current HTML element or ASP.NET control you are working with:


In the properties grid above you'll notice that some values are duplicated multiple times - with red arrows striking out previous values.  This indicates that a parent CSS rule setting is being overridden by another CSS rule's value.  You can see both the original value as well as the overridden one in the summary view at the bottom. 

You can click on the individual values to see where in the CSS precedence hierarchy this value was inherited from or overridden.  In the example below you can see that the final color for the current element that my cursor is on is a dark brown color.  If I select this final color value, the CSS properties window will draw a blue box in the applied-rules list above indicating that this setting is set in the "singlecontent h3" rule:


If I click on the lighter brown color setting that this rule overrode (and which has the red strike-thru), you can see that it originated with the page's HTML body CSS rule (notice how the body rule below is selected in the applied rules list when I select the overridden value below):


Please read this dedicated CSS Properties Window blog post to learn even more how to use the CSS property window.

CSS Source View Intellisense

The HTML designer supports the ability to select an element or control in design-view, and graphically select a rule from the CSS list to apply to it. 

You'll also find when in source mode that you now have intellisense support for specifying CSS class rules:


This is true for both HTML element (like above), as well as with ASP.NET server controls:


This CSS intellisense is supported in both regular HTML / ASP.NET pages, as well as when working with pages based on master pages and nested master pages.

Nested Master Page Support

Earlier this month I wrote a dedicated blog post that covered the new VS 2008 Nested Master Page Support.  All of the above designer and CSS features obviously work with that as well:


Summary

The above post provides a quick look at some of the new HTML designer and CSS tool support in VS 2008 (all of the above features also ship with the free Visual Web Developer 2008 Express edition). 

Because VS 2008 now has multi-targeting support you'll be able to use these feature immediately without having to install .NET 3.5 on your servers.  You can open existing ASP.NET 2.0 projects in VS 2008, have VS 2008 continue to target .NET 2.0 as the runtime target, and begin using these features immediately.

Over the next week I'll also be starting a new multi-part blog series that covers the new <asp:listview> control that ships as part of ASP.NET in .NET 3.5.  One of the big benefits of the <asp:listview> is that it enables developers to have total control over the HTML output emitted in data scenarios.  This works well with all of the new CSS tool features above, and enables you to more easily create great looking web sites and applications.

For More help

usamawahabkhan@gmail.com

Silverlight XAML Controls

Silverlight has many User Interface (UI) controls. .NET programmers already familiar with ASP.Net or (especially) WPF will find using the Silverlight controls very natural and straight forward.

Silver light Controls (split in two to make it easier to view)
Functionality right out of the box. Moreover, all of the standard controls can be modified in
numerous ways to meet your needs.
The look and feel of the control can be tweaked through styles or can be entirely redesigned
through templates, and the behavior of the controls can be modified through event handlers. In
the rare cases when none of that is enough, you can create (or derive) your own customized
controls as well.
Creating the First Example - A Grid with Controls
Open Visual Studio 2008 and click on Create Project and then in the new project window you'll want to create a C# project using the Silverlight Application Template.
Pick a location for your application and give it a meaningful name; be sure that you are building
against the latest framework.

Creating a New Silverlight Project

When you click OK you will next be asked if you'd like to generate a Web Site or a Web
Application (using the top radio button) or just a test page (using the bottom radio button) or if
you'd like to link to an existing web site; all as shown in the next figure.

Choose Simple HTML Test Page
Visual Studio create a simple application foryou. If Page.xaml doesn't open utomatically, double click on it in the Solution Explorer. You should find that Visual Studio has guessed that you want a grid as your main container, and has created one for you and named it LayoutRoot. (Also note that the very first declaration in each "page" is a UserControl.
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
In fact a Page is a UserControl, and we'll return to that relationship in a later tutorial.
The Grid definition created by Visual Studio 2008 looks like this:




Defining Rows and Properties
You define the Rows for a table inside the Grid.RowDefinitions element. For each Row, you add
a RowDefinition element, which itself may have various properties, including a specific height,
or if you prefer you may set the height to be proportional to the available space or to take all the
space not taken by other rows.

Height="Auto"With Auto, the Grid’s space is distributed evenly based on the size of the content within the row.
Star or Proportional Sizing
In proportional sizing the value of a column or row is expressed in Xaml as *.
However, you can give twice the space to one column or row as another by using 2* (or a 5:7
ration by using 5* and 7*).

If you combine this with a Minimum or Maximum Height you get finer control over the limits of
the row's range of sizes,



Minimal or Controlled space
By default child elements of grid take up the least amount of space necessary to to accommodate
the largest content within a cell in a given row or column. You can take greater control over
positioning, however, by using the margin and alignment properties as described below
Sizing Units

To provide the most flexibility, Grid columns and rows are sized by GridLength objects which use the GridUnitType, which in turn allows you to choose among:
• Auto (size based on the size properties of the object being placed in the grid)
• Pixel (size in pixels)
• Star (size based on a weighted proportion of the available space)
designating, if we choose, the minimum and maximum dimensions of each.
To see the effect of all this we'll create five rows using different sizing rules. We'll also create
three columns with no sizing rules at all (!). We'll then fill our grid with controls and take a look
at some of the effects. Here is the code, which we'll take apart piece by piece.
The Xaml for EasyGrid



The result of the Xaml code is shown in

The Xaml as Design

First, it is important to understand that the Xaml shown in 1st Example is all that is needed to
produce the Silverlight control shown in all Figure. It is true that you can't see the rows and
columns, but that is easily remedied. Find the declaration of the Grid and set its ShowGridLines
property to True (Intellisense will help as shown inFigure 1-5

Adding Property ShowGridLines and setting it True
When you do, the grid lines become visible; which can be very useful during design, as long as
you remember to set the property to false before you post your Silverlight application!
ShowGridLines Makes The Alignment Very Visible
Unpacking the Xaml
The first lines create the Grid and define how the rows will share the space.

As described above, the RowDefinitions define five rows. The first has a fixed height of 50. The
second and third will float, but in a 3:4 proportion with one another, but each with a maximum
height of 70. The next row will take all the remaining space, but will never be allowed to shrink
to less than 30 nor grow to more than 50. The final row will size itself to the object placed in the
row, but yet is constrained to no less than 5 and no more than 30.
After the column definitions we define a TextBlock and a TextBox. We'll discuss these controls
in more depth later, but the former is typically used as a label and the latter is used to allow the
user to put in text.
x:Name="FirstNamePrompt "
Grid.Row="0"
Grid.Column="0"
Text="First Name:"
Margin="5"/>
The TextBlock has five parameters. They can be aligned one below the other, or strung out all in
a line, any way you like. The first parameter is the name (FirstNamePrompt) and is used to
allow you to address the object in code. If you give an object in Xaml a name, and save the file,
that object is available with no further declaration in your methods
Thus, if you save this file, you will be free to write
FirstNamePrompt.Text=”Hello”
From any method of this class and the compiler will know exactly what you mean!
The Grid.Row and Grid.Column properties are called extended properties and are really
"borrowed" from the immediately surrounding grid to position the TextBlock inside the
appropriate cell.
The Text property does just what you expect, it fills the TextBlock with that text.
Margin is a fascinating property, and we'll return to it a couple times. For now, I'll mention that it
takes three forms:
• A single value, which gives a margin of that value "all around" - that is left, right, top and
bottom
• Two values in which case the first is divided evenly among the left and right margin and
the second is divided evenly among the top and bottom
• Four values, in the order Left, Top, Right, Bottom.
The TextBlock label in the first column is followed by an (input) TextBox in the second column.
The properties are very similar except that you must declare the width of your TextBox and we
choose here to give the TextBox a background color.
The next pair are much like the first.
The third row is filled by a TextBlock and two CheckBox controls. Note that they are aligned by
setting their VerticalAlignment properties and that the first CheckBox has its IsChecked property
set to True so it will be checked when the page is first shown.
The fourth row has a TextBlock that displays Hello and the final row has a TextBlock that
displays World, but does so setting the FontFamily, FontSize and FontWeight.


By:
Usama Wahab Khan and Atif Shahzad
Sr.Software Developer

ASP.NET

Friday, July 3, 2009

An application is defined as the set of files in an IIS virtual directory and its subdirectories. The files that constitute an ASP.NET application typically include:
•A Global.asax file containing application-level program directives, handlers for application and session-level events, and declarations of objects that are globally accessible to all parts of the application.
•A Config.web file containing configuration information.
•One or more ASPX files containing Web Forms.
•One or more code files written in C# containing the application's code.
Code files aren't always present in the virtual directory because code can optionally be placed in the ASPX files. But most Web Forms applications especially those created with Visual Studio.NET segregate code and data into separate files
Global.asax is to ASP.NET what Global.asa is to ASP. If you want to trap events such as Application_Start, Application_End, Session_Start, and Session_End (which are fired when applications start and stop and sessions begin and end) you put the event handlers in Global.asax. Typical uses for these event handlers include initializing state for each user and manipulating program counters. Config.web is new to ASP.NET. It's an XML-formatted file that stores an application's configuration settings. It's a welcome improvement over ASP, whose insistence on storing configuration data in the IIS metabase makes moving an application from one machine to another a chore. Plus, because it's a text file, Config.web can be edited with a text editor like Notepad.
Application Pages
Each ASPX file included in a Web Forms application constitutes one page of the application. The first time a page is requested, ASP.NET dynamically generates a class to represent that page by deriving from System.Web.UI.Page. After compiling the derived class and caching the compiled executable in a special directory (so subsequent requests for the same page will execute much faster), ASP.NET instantiates the class and executes it to generate HTML to return to the client.
The HTML included in the output stream comes from the HTML present in the ASPX file, the page's controls, and any scripts that write out HTML of their own. After it's executed, the instance of the page object is discarded. Thus, a page object's lifetime lasts from the time it's instantiated following each new request, until the request is complete.
During its lifetime, a page undergoes several distinct phases. As it enters each new phase, the page fires an event that can be processed with a server-side script. For Web Forms developers, the most important page-level event is Page_Load, which is called each time the page is instantiated. Because Page_Load is called before the page is rendered to the client, it's a great place to perform any one-time initializations that need to happen before rendering takes place. Developers can respond to Page_Load events by implementing a handler in a script:


A common use for Page_Load events is to query a database for information needed to initialize one or more of the page's controls. Page_Load can even be used to populate the page with controls programmatically.
Because ASPX scripts execute in the context of a class derived from System.Web.UI.Page, they can call System Web.UI.Page methods and access System.Web.UI.Page properties. Those properties include Request, Response, Server, Application, and Session, which provide access to the ASP objects of the same name.
The Page class also exposes a Boolean property named IsPostBack that's often used by Page_Load handlers. In many cases, initializations performed in Page_Load only need to happen when the page is requested anew, not during postbacks. IsPostBack tells you whether your code is executing within a postback (IsPostBack==true) or in response to a new request (IsPostBack==false). The following Page_Load handler initializes a control with the results from a database query, but only if it's called outside of a postback:

Such code is often used to avoid requerying a database (and reinitializing a form's controls) when postbacks occur.
Page-level Directives
For the most part, the component of ASP.NET that compiles pages into executable form the page compiler does its work behind the scenes and without any input from you. However, you can add your two cents to the settings that it uses by including page-level directives in your ASPX files. The syntax for page-level directives is:

For example, including the following directive at the top of an ASPX file turns tracing on.


Tracing is a handy debugging aid that enables Web Forms to write trace output to Web pages. Similarly, the following statement enables tracing and identifies C# as the default language for scripts embedded within the page.

For a complete description of all the options that ASP.NET places at your disposal through page-level directives, consult the document titled " ASP.NET Page Syntax".
In some cases, page-level directives are optional. In certain scenarios, however, they're very much required. Web Forms that use custom controls, for example, require Register directives to define tag prefixes for those controls.
Separating Code and Data
One feature that's made accessible by page-level directives is code-behind, which enables Web Form code and data to be placed in separate files you can separate the two by moving the code to a CS file
Controls
The .NET Framework class library, which provides the classes common to all .NET applications, contains several classes that represent server controls. These classes are divided into two categories: HTML controls and Web controls.



HTML controls are created from classes in the .NET Framework class library's System.Web.UI.HtmlControls namespace. All HTML control classes derive, either directly or indirectly, from System.Web.UI.HtmlControls.HtmlControl. HTML control classes are instantiated by adding RunAt="server" to ordinary HTML tags. For example, the following statement declares a standard HTML text input field.

But this statement declares an instance of HtmlInputText.

Within an tag of this type, you can use standard HTML attributes such as Name and Value. You can also use attributes that map to the properties defined in the corresponding HTML control class. For example, the statement

assigns the value "UserName" to the HtmlInputText property named ID. This ID can be used to reference the control in server-side scripts. The following C# statement reads the text that the user entered into the control.
string strUserName = UserName.Value
documents all the HTML control classes and the HTML tags to which they correspond. These classes are provided primarily to ease the chore of migrating existing Web applications (particularly ASP applications) to ASP.NET. For example, rather than replacing all instances of with , you can simply add RunAt="server" to the existing tags to convert them into living, breathing Web Forms controls.

HTML controls are little more than glorified wrappers around existing HTML tags, but Web controls are richer and more ambitious in scope. For example, you can use a Calendar control to display calendars in Web Forms and let users pick dates using a visual (and self-contained) UI. Some Web controls even adapt themselves to the browser that they're rendered to. For example, a RequiredFieldValidator control rendered to an uplevel browser includes client-side script that validates user input locally. The same control rendered to a browser that doesn't support scripting, however, uses round-trips to the server to flag blank fields.
The attributes that you can apply to tags when declaring Web controls are determined by the properties defined in the respective control classes. For example, because the TextBox class exposes properties named TextMode and Text, all of the following statements are valid:

The properties exposed by individual controls vary from control to control, but all Web controls, with the exception of Repeater, inherit a common set of properties from the base class WebControl.
Syntax is important when using these properties, particularly the Font, Width, Height, and XxxColor properties. The Font property has subproperties named Bold, Italic, Name, Names, Size, Strikeout, Underline, and Overline. To assign a value to a subproperty, separate the property name (Font) and the subproperty name with a hyphen, as in

The Font-Size property can be specified using pixels as the unit of measurement using either of the following syntactical conventions:

Or it can be expressed in points by replacing px with pt:

Width, Height, and BorderWidth values can be expressed in pixels, points, or percentages. Pixels is the default, so omitting px, pt, and % is the equivalent of writing out px.

Both HTML and Web controls support an event model that permits control events, such as pushbutton clicks, to be connected to server-side event handlers. You've seen one example of this already in below figure, where an OnClick attribute was used to connect the Calculate button to the OnCalculate method. The .NET SDK lists all the events defined by all the control types. In general, you can connect an event to a handler by prefixing the event name with On and using it as an attribute. For example, ListBox controls fire SelectedIndexChanged events each time the selection changes. The following statement connects SelectedIndexChanged events to a handler named OnNewSelection:

Note the parameter that sets AutoPostBack equal to True. To avoid unnecessary round-trips to the server, ListBox selection changes only prompt postbacks if AutoPostBack is True. In the absence of automatic postbacks, a server-side script will only see SelectedIndexChanged events when the form is posted back to the server in response to other stimuli. AutoPostBack is supported by CheckBox, CheckBoxList, DropDownList, ListBox, TextBox, RadioButton, and RadioButtonList controls. In every case, it defaults to False. Don't forget to toggle AutoPostBack on if you want to handle events from these control types. Also, be aware that AutoPostBack does nothing in downlevel browsers that don't support JavaScript.
Space constraints don't permit me to examine every one of the Web control classes in detail, but once you grasp the basics, the rest is easy to figure out. The following sections will give you a quick survey of the Web control classes in the .NET Framework class library and sample code showing how to use them in Web Forms applications.
Label Controls
Label controls, which are denoted by tags, display text in Web pages. You specify the control's text using System.Web.UI.WebControls.Label's Text property. The following statement creates a Label control and assigns it the text "Hello":

To modify a Label control's text during the course of an application's execution, you can simply assign the control an ID and use a server-side script to write a new value to the control's Text property:


// In a C# script

HyperLink controls let you place hyperlinks (the equivalent of tags) in Web pages. Properties specific to HyperLink include Text, NavigateUrl, ImageUrl, and Target. Text specifies the control text, and NavigateUrl identifies the URL that the hyperlink points to.

If you'd like, you can replace Text with ImageUrl to display the hyperlink as an image instead of a text string:

You can use the Target property to reference a window or frame at the URL named by NavigateUrl. For example, adding a "Target=_new" attribute to an tag opens the resource in a new browser window.
Image Controls
Image controls are to Web Forms as tags are to HTML. Their purpose is to display images in Web pages. Control-specific properties include AlternateText, ImageAlign, ImageUrl, and Font. The following statement declares an Image control whose alternate text (the text displayed when the image file isn't available and when you mouse over the image) is "Company Logo" and whose appearance comes from Logo.jpg:

You can use the ImageAlign attribute to specify the image's alignment with respect to the text that surrounds it, and the Font property to change the font used for the alternate text.
TextBox Controls
TextBox controls are the Web Forms equivalent of and
Setting TextMode to "password" tells the control to act as a password control by displaying asterisks instead of characters:

The "multiline" setting creates a multiline text input field:

To read text from a TextBox control in a server-side script, simply read the control's Text property:

If the text in a TextBox has changed when the form is posted back to the server, the control fires a TextChanged event that can be handled by a script. The following example demonstrates how to synchronize the contents of a label control and a TextBox control by updating the label control each time a postback occurs. Note the AutoPostBack setting:

Be aware that TextChanged events are not fired each time a new character is typed into the TextBox. AutoPostBack="true" causes a postback to occur only when the TextBox loses the input focus after its contents are modified.
CheckBox and CheckBoxList Controls
CheckBox controls add checkboxes to Web pages. Useful CheckBox properties include Text, TextAlign, and Checked. The following statement creates an unchecked checkbox:

This one creates a checkbox that's checked and whose text is aligned to the left (rather than the right) of the checkbox:

To check the state of a checkbox from a server-side script, read the Checked property, which is a Boolean:

CheckBox controls fire CheckedChanged events when they're checked and unchecked. Use OnCheckedChanged to connect CheckedChanged events to a handler implemented in a server-side script. Also, don't forget to set AutoPostBack to True
The CheckBoxList control lets you display groups of checkboxes and exercise control over the group's layout. ListItem statements define the individual checkboxes within the group. Setting a ListItem's Selected property to True checks the corresponding checkbox:

Two CheckBoxList properties affect the layout of the checkboxes: RepeatColumns and RepeatDirection. RepeatColumns specifies the number of columns the checkboxes are to be divided into (default=1); RepeatDirection specifies whether the checkboxes are to be laid out in row-first order (RepeatDirection="horizontal") or column-first order (RepeatDirection="vertical"). Vertical is the default. Use the CellPadding and CellSpacing properties to fine-tune the spacing between checkboxes.
RadioButton and RadioButtonList Controls
RadioButton controls () enable users to select from a group of mutually exclusive options. RadioButtons behave very much like CheckBoxes (in fact, the RadioButton class even derives from CheckBox), but they add one important characteristic of their own: when one RadioButton is checked, the other RadioButtons in the same group are automatically unchecked. To support grouping, RadioButton adds one property, GroupName, to the list of properties it inherits from CheckBox. The following example creates two groups of RadioButtonsâ€"one containing three controls and the other containing two and checks one RadioButton in each group:

To programmatically determine whether a RadioButton is selected, read the button's Checked property. To trap notifications indicating that a RadioButton's state has changed, use the OnCheckChanged and AutoPostBack attributes.
RadioButtonList controls provide an alternate means for creating and grouping RadioButtons. The following code is equivalent to the previous code:

Note the lack of GroupName attributes. They're not needed with RadioButtonLists because grouping is implicit (each RadioButtonList constitutes its own group). Also be aware that like CheckBoxList controls, RadioButtonLists feature RepeatColumns and RepeatDirection properties that you can use to control the buttons' layout, as well as CellPadding and CellSpacing properties for tweaking their spacing. To find out which button in a RadioButtonList is selected, assign the RadioButtonList an ID and read its SelectedIndex property from a server-side script. SelectedIndex returns the zero-based index of the button that's selected.
ListBox and DropDownList Controls
ListBox and DropDownList controls are analagous to
These statements create a DropDownList containing the same items:

This server-side script, written in C#, modifies a pair of Label controls whose IDs are "Label1" and "Label2" to report which items were selected from the lists:

To permit a user to select multiple items from a listbox, add

In a derived class, you can use the SelectedIndices property that ListBox inherits from ListControl to identify the items selected in a multiple-selection ListBox. But because SelectedIndices is declared protected rather than public, you can't use it with an ordinary ListBox. (Note: In Beta 2, SelectedIndices will probably change from protected to internal, in which case it wouldn't even be available in classes derived from ListBox.) To read the selection from a multiple-selection ListBox, use the control's Items collection to enumerate the ListBox items and check each item's Selected property.
ListBoxes, DropDownLists, CheckBoxLists, and RadioButtonLists fire SelectedIndexChanged events upon the next server postback when the selection changes. You can add an OnSelectedIndexChanged attribute to a tag (for example, ) to wire up a handler. When the handler is activated, use the SelectedIndex or SelectedItem property to determine which item is currently selected.
Sometimes it's useful to fill list controls programmatically, based on information gathered at runtime. Here's one way to populate a ListBox from a server-side script:

And here's another wayâ€"one that utilizes System.Collections.ArrayList:

This sample works because ListBox and other ListControl-derived classes have properties named DataSource that can be initialized with a reference to any object that implements an ICollection interface, and because ArrayList and many other collection types provided by the .NET Framework class library implement ICollection. Calling the control's DataBind method tells the control to enumerate the collection's items and to bind them by displaying them. I'll have more to say about data binding in the section on list-bound controls later in this article.
Button, LinkButton, and ImageButton Controls
Three server controls Button, LinkButton, and ImageButton can be used to submit forms to the server to allow server-side processing to take place. All three control types do essentially the same thing; the difference is how they render themselves to the screen. Button controls resemble standard pushbuttons. LinkButtons look like hyperlinked text, and ImageButtons derive their looks from user-supplied images. When clicked, all three controls fire Command and Click events that can be handled in server-side scripts. In addition, ImageButtons transmit x and y coordinates revealing where in the image the click occurred.
All three classes expose properties named CommandArgument and CommandName that can be used to customize the information passed in Command events. In addition, Button and LinkButton expose their text through Text properties. ImageButton lacks a Text property but offers ImageUrl and ImageAlign properties instead.
The following code creates a Button and a LinkButton and connects them to a Click handler named OnSubmit:

An ImageButton can't be connected to the same Click handler as a Button or LinkButton because its Click event is prototyped differently: it receives an ImageClickEventArgs rather than an EventArgs. If the handler wants to know exactly where the click occurred, it can obtain the x and y coordinates from the ImageClickEventArgs:

The coordinates encapsulated in an ImageClickEventArgs are measured in pixels and are relative to the upper-left corner of the ImageButton.
Table Controls
Table controls () create HTML tables and, combined with TableRow and TableCell controls, provide a functional alternative to

, ,
, and tags. The following example creates a table containing two rows and two columns:

By default, a table defined this way has no border. To add a border, set the BorderWidth attribute to 1.
If you'd like to add a background image as well, use the BackImageUrl attribute. BackImageUrl is one of several properties that Table adds to those it inherits from WebControl. Others include CellPadding, CellSpacing, GridLines, HorizontalAlign, and Rows. The TableRow and TableCell classes expose properties of their own that provide a high degree of control over the table's appearance and enable scripts to programmatically alter or enumerate a table's contents.
The following creates a table identical to the previous one, but assigns text to the table's cells using TableCell's Text property:

Defining a table this way (and assigning IDs to TableCell controls) enables server-side scripts to easily modify a table's contents by changing the Text properties of individual TableCells. Also note that you can use TableHeaderCell controls in lieu of TableCells to define table headers. TableHeaderCell controls evaluate to
tags. Many browsers render and tags identically.
Panel Controls
Panels are controls that are used to create logical groupings of other controls. A Panel generally has no UI of its own, but it is useful for controlling the visibility of other controls on the page. For example, suppose you declare three

To hide these Label controls, set their Visible properties to False:

But if you grouped the Label controls with a Panel control, one statement would make all three disappear from sight:

Calendar Control
The controls that I've discussed thus far are little more than wrappers around simple HTML tags. Not so with the Calendar control. A single Calendar control expands to more than 100 lines of HTML when it's rendered to a browser.
Calendar controls are ideal for letting users choose dates and date ranges using a highly visual UI. Getting a basic Calendar control up and running in a Web page is simplicity itself:

But this simple example belies the sheer number of options that the Calendar class offers. Calendar defines 28 properties in addition to those it inherits from its base class. Many Calendar properties have subproperties that further expand the number of options available. These properties and subproperties let you customize the control's appearance in just about any way you like. They also enable you to get or set the date (or date range) selected in the control. The Calendar class also defines events named SelectionChanged and VisibleMonthChanged that allow server-side scripts to respond to selection changes and to changes in the month that is currently displayed.

full-blown Web Forms application that displays a stylized calendar and responds to SelectionChanged events by updating a Label control positioned just above the Calendar control. Clicking the Submit button activates a server-side script that reads the currently selected date from the control and displays it in the browser in "long date" format

AdRotator Control
I won't say a lot about the AdRotator control other than to point out that it's functionally similar to the ad rotator control that comes with ASP. Its purpose is to display rotating banner ads using configuration parameters encoded in an XML file.
List-Bound Controls
One of the tasks that Web applications are asked to perform most frequently involves retrieving data from a database and displaying it in a Web page. ASP.NET does several things to help out with this mundane but important chore. First, it interoperates with a new data access technology called ADO.NET that was specifically designed to meet the needs of data-handling applications deployed over the Web. Second, it genericizes the concept of a data source so applications can work with a wide range of data providers, from relational databases to in-memory XML data stores to simple arrays. Finally, it includes a family of Web controls that know how to read data from data sources and render visual representations to Web pages. Members of that family are known as the list-bound controls.
Three of the classes in System.Web.UI.WebControls represent list-bound controls: Repeater, DataList, and DataGrid. A full treatment of these classes could fill a small book, but I want to give you a taste of what they're like, because in addition to being among the most complex classes in the .NET Framework class library, they're also some of the most useful especially to developers building e-commerce applications.
For starters, suppose you want to create a Web page that retrieves a set of records from a back-end database and displays those records in a table. You could use ASP and ADO to query the database and build the table yourself, or you could use ADO.NET and a DataGrid control and let the DataGrid build the table. The database used in this example is the Pubs database that comes with the .NET SDK. The page's Page_Load handler uses a SQL SELECT command to query the database for a list of all the records in the Titles table. (Note the if clause that prevents the query from being performed during postbacks.) Each record returned from the query contains information about one bookâ€"its title, price, publication date, and so on. The statement

connects the results of the query to the DataGrid control, and the statement

binds the control to the data. The DataGrid itself is declared with an tag and assigned the ID MyDataGrid.
The DataGrid control renders back to the browser as a standard HTML table containing all the data returned by the query, which currently consists of all the rows and columns (including column names) in the Titles table of the Pubs database.

DataGrid Control
Table shows far more information than it needs to, and it could definitely be formatted more attractively. Plus, if I want customers to buy books from my Web page, they'll need a way to add items to a shopping cart. I won't go so far as to implement a full-blown shopping cart, but I'll at least lay the groundwork for you.
The tag now includes a long list of attributes used to customize the table's appearance. The AutoGenerateColumns attribute is particularly important, because setting it to False prevents the DataGrid from automatically generating columns based on the fields it finds in the database. Now I can control the columns displayed by adding and tags to the tag. A BoundColumn is a DataGrid column that is bound to a particular field in the database specifically, to the field identified by the BoundColumn's DataField property. A ButtonColumn contains buttons instead of ordinary text. This ButtonColumn inserts an "Add to Cart" command into each row of the table. Clicking a button activates the event handler, OnItemAction, which displays the name of the item that the user selected at the bottom of the page.

Selecting an Item
The many attributes used in the are emblematic of the myriad formatting options that the DataGrid class offers. In particular, note how the control's HeaderStyle, ItemStyle, and AlternatingItemStyle properties (and their subproperties) are used to customize the appearance of the rows. Also note how ItemStyle-HorizontalAlignment is used to right-align the numbers in the Price column and center the buttons in the Action column, and how DataFormatString is used to format the numbers in the Price column as currency values. Unlike Windows-based controls, which offer an extremely limited number of formatting options, DataGrid controls put you in charge of virtually every aspect of their appearance.
These examples barely scratch the surface of what you can do with DataGrid controls, and they don't even address DataList and Repeater controls. But hopefully you get the idea. List-bound controls ease the chore of displaying structured data. The more you use ASP.NET, the more you'll appreciate the power of these controls. For more information about list-bound controls and examples demonstrating how to use templates to further customize their appearance, read "Using the ASP+ List-Bound Controls".
Validation Controls
The Web controls family includes a set of controls whose purpose isn't to solicit input, but to validate it. Consider the mortgage calculator presented earlier in this article. A real-life version should display an error message if the user fails to fill in a field or fills it in improperly. That's what validation controls are for.
RequiredFieldValidator controls to check for blank fields, and RegularExpressionValidator controls to make sure that entries are well-formed specifically, that the Principal and Months fields contain only numbers and that the Rate field contains numbers and a period. RequiredFieldValidator controls verify that the content of the controls that they're attached to is non-null, while RegularExpressionValidator controls validate a control's content against a regular expression provided by the programmer. (Unfortunately, RegularExpressionValidator controls can't be used to ensure that the fields are also filled in.) For example, setting a RegularExpressionValidator's ValidationExpression property to [0-9]* specifies that any number of digits (and digits only) will be accepted; setting it to [0-9]\.[0-9]* limits valid text to strings of the form *.*, where * is any numeric character.
the Calculate button is clicked but an entry is missing: an error message flags the offending field. You control the error message and its placement. Among other things, this means that you no longer need code in OnCalculate to check for null strings. If the Calculate button is clicked and a field is blank, the form is never submitted, therefore the script isn't executed.
Validating Input
each TextBox control now has corresponding RequiredFieldValidator and RegularExpressionValidator controls. The table used to align the form's control has been extended with a third column that hosts the validators. Before rendering themselves to the output stream, validator controls check to see whether the browser that they're rendering to supports scripting. If the answer is yes, they return client-side script that performs validation checking locally. If the answer is no, they omit the client-side script and return HTML that forces a return trip to the server so the server can do the checking. Either way, you win. You get a page that works no matter what kind of browser is being used. And you get a page that works more efficiently with intelligent browsers.
In addition to the RequiredFieldValidator and RegularExpressionValidator controls, the .NET Framework also provides:
•CompareValidator control, which validates input by comparing it to a value i another control or a value that you specify.
•RangeValidator control, which verifies that an input value falls within a specified range.
•CustomValidator control, which validates input using an algorithm you supply.
•ValidationSummary control, which displays a summary of all the validation errors encountered on a page. For more information regarding these controls, visit MSDN® Online's Web Forms Validation page.

Custom Controls
It should be abundantly clear by now that the System.Web.UI.WebControls namespace includes a rich variety of Web controls that ease the chore of building sophisticated Web Forms. But there's more. If none of the existing controls fit the bill, you can write Web controls of your own. Such controls are variously referred to as custom controls, custom server controls, or custom Web controls. A full treatment of custom controls merits an article of its own.
This example, Headline.aspx, is a simple Web Form that employs a custom control named Headline. The Register directive equates the tag prefix "demo" to the namespace MSDNMagControls. The source code for the Headline control is contained in Headline.cs. That file declares a namespace named MSDNMagControls, which contains a class named Headline. Headline is derived from System.Web.UI.Control, which forms the basis for all server controls. To render the Headline control to the browser, the framework calls the control's virtual Render method and passes a reference to an HtmlTextWriter object the control can use to write text to the HTML output stream. Headline overrides the Render method and outputs the text stored in a field named _Text, which is exposed through a property named Text, surrounded by

tags. The result? In Headline.aspx,

However, the actual rendering is done by the control. Headline could be extended with additional properties, methods, and even events to make it a first-class Web control.
Something that's not obvious from the source code figures is how the ASPX file knows where to find the compiled CS file containing the custom control. In order for this example to work, you must compile the CS file into a DLL and store it in a directory named \bin under the application's virtual root directory. The following command uses the C# compiler to compile Headline.cs, creating a DLL named MSDNMagControls.dll:

Once the DLL is created, placing it in the \bin directory makes it available to Web Forms that are part of the corresponding app .
User Controls
So far the term "control" has referred either to HTML controls or Web controls. Web Forms support a third type of control, which the documentation refers to as user controls. A user control is a chunk of reusable Web Forms code packaged in an ASCX file. Generally, it's all or part of a form without the
tags. To employ a user control, you open an ASPX file and add a Register directive that registers a tag name and tag prefix for the user control and identifies the user control's ASCX file. You then declare an instance of the user control by inserting a tag containing the user control's tag name and prefix into a form in the ASPX file.
User Control Login Screen.
The user control contributes the part of the form that appears between the horizontal rules. Everything else comes from the ASPX file. In Login.aspx, this statement registers the user control.

This statement declares an instance of it and initializes its background color.

BackColor is a valid attribute because the script in Login.ascx implements a property of that name and maps it to the BackColor property of the table used to align the user control's controls. The ASCX file also defines properties named UserName and Password. UserName is used in the page's Page_Load handler to read the name that the user entered.
User controls let you package snippets of Web Forms in such a way that they can be reused as components in other Web Forms. Additionally, user controls can contribute more than just a user interface. The user control in Login.ascx includes validation logic that rejects the login (prevents the form from being submitted) if either input field is blank, if the user name contains less than five characters, or if the password contains less than eight. In the real world, a user control such as this one could be enhanced to perform real authentication. Then, building a screen that knows how to validate logins would be as simple as adding the user control to a form.
As a syntactical matter, note that unlike ASPX files, ASCX files can't include Page directives. They can, however, contain Control directives that accomplish the same objective.
By
Usama Wahab Khan and Atif Shahzad