Asp.Net

ASP.NET - Basic Controls

In this section, we will discuss the basic controls available in ASP.NET

Button Controls:


ASP .Net provides three types of button controls: buttons, link buttons and image buttons. As the names suggest a button displays text within a rectangular area, a link button displays text that looks like a hyperlink. And an Image Button displays an image.
When a user clicks a button control, two events are raised Click and Command.
Basic syntax for button controls:
<asp:Button ID="Button1" runat="server" 
            onclick="Button1_Click" Text="Click" />
Common Properties of the Button control:
PropertyDescription
TextThe text displayed by the button. This is for button and link button controls only.
ImageUrlFor image button control only. The image to be displayed for the button.
AlternateTextFor image button control only. The text to be displayed if the browser can't display the image.
CausesValidationDetermines whether page validation occurs when a user clicks the button. The default is true.
CommandNameA string value that's passed to the Command event when a user clicks the button.
CommandArgumentA string value that's passed to the Command event when a user clicks the button.
PostBackUrlThe URL of the page that should be requested when the user clicks the button.

Text Boxes and Labels:


Text box controls are typically used to accept input from the user. A text box control can accept one or more lines to text depending upon the setting of the TextMode attribute.
Label controls provide an easy way to display text which can be changed from one execution of a page to the next. If you want to display a text that does not change, you use the literal text.
Basic syntax for text controls:
<asp:TextBox ID="txtstate" runat="server" ></asp:TextBox
Common Properties of the Text Box and Labels:
PropertyDescription
TextModeSpecifies the type of text box. SingleLine creates a standard text box, MultiLIne creates a text box that accepts more than one line of text and the Password causes the characters that are entered to be masked. The default is SingleLine.
TextThe text content of the text box
MaxLengthThe maximum number of characters that can be entered into the text box.
WrapIt determines whether or not text wraps automatically for multi-line text box; default is true.
ReadOnlyDetermines whether the user can change the text in the box; default is false, i.e., the user can change the text.
ColumnsThe width of the text box in characters. The actual width is determined based on the font that's used for the text entry
RowsThe height of a multi-line text box in lines. The default value is 0, means a single line text box.
The mostly used attribute for a label control is 'Text', which implies the text displayed on the label.

Check Boxes and Radio Buttons:


A check box displays a single option that the user can either check or uncheck and radio buttons present a group of options from which the user can select just one option.
To create a group of radio buttons, you specify the same name for the GroupName attribute of each radio button in the group. If more than one group is required in a single form specify a different group name for each group.
If you want a check box or radio button to be selected when it's initially displayed, set its Checked attribute to true. If the Checked attribute is set for more than one radio button in a group, then only the last one will be selected.
Basic syntax for check box:
<asp:CheckBox ID= "chkoption" runat= "Server"> 
</asp:CheckBox>
Basic syntax for radio button:
<asp:RadioButton ID= "rdboption" runat= "Server"> 
</asp: RadioButton>
Common Properties of the Check Boxes and Radio Buttons:
PropertyDescription
TextThe text displayed next to the check box or radio button.
CheckedSpecifies whether it is selected or not, default is false.
GroupNameName of the group the control belongs to.

List Controls:


ASP.Net provides the controls: drop-down list, list box, radio button list, check box list and bulleted list. These control let a user choose from one or more items from the list.
List boxes and drop-down list contain one or more list items. These lists could be loaded either by code or by the ListItem Collection Editor.
Basic syntax for list box control:
<asp:ListBox ID="ListBox1" 
      runat="server" 
      AutoPostBack="True" 
      OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">
</asp:ListBox>
Basic syntax for a drop-down list control:
<asp:DropDownList ID="DropDownList1" 
     runat="server" 
     AutoPostBack="True" 
     OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
Common Properties of List box and Drop-down Lists:
PropertyDescription
ItemsThe collection of ListItem objects that represents the items in the control. This property returns an object of type ListItemCollection.
RowsSpecifies the number of items displayed in the box. If actual list contains more rows than displayed then a scroll bar is added.
SelectedIndexThe index of the currently selected item. If more than one item is selected, then the index of the first selected item. If no item is selected, the value of this property is -1.
SelectedValueThe value of the currently selected item. If more than one item is selected, then the value of the first selected item. If no item is selected, the value of this property is an empty string("").
SelectionModeIndicates whether a list box allows single selections or multiple selections.
Common Properties of each list item objects:
PropertyDescription
TextThe text displayed for the item
SelectedIndicates whether the item is selected.
ValueA string value associated with the item.
It is important to notes that:
  • To work with the items in a drop-down list or list box, you use the Items property of the control. This property returns a ListItemCollection object which contains all the items of the list.
  • The SelectedIndexChanged event is raised when the user selects a different item from a drop-down list or list box.

The List Item Collections:


The ListItemCollection object is a collection of ListItem objects. Each ListItem object represents one item in the list. Items in a ListItemCollection are numbered from 0.
When the items into a list box are loaded using strings like: lstcolor.Items.Add("Blue") . then both the Text and Value properties of the list item are set to the string value you specify. To set it differently you must create a list item object and then add that item to the collection.
The ListItem Collection Editor is used to add item to a drop-down list or list box. This is used to create a static list of items. To display the Collection Editor select Edit item from the smart tag menu, or select the control and then click the ellipsis button from the Item property in the Properties window.
Common Properties of List Item Collection:
PropertyDescription
Item(integer)A ListItem object that represents the item at the specified index.
CountThe number of items in the collection.
Common methods of List Item Collection:
MethodsDescription
Add(string)Adds a new item to the end of the collection and assigns the string parameter to the Text property of the item.
Add(ListItem)Adds a new item to the end of the collection.
Insert(integer, string)Inserts an item at the specified index location in the collection, and assigns the string parameter to the Text property of the item.
Insert(integer, ListItem)Inserts the item at the specified index location in the collection.
Remove(string)Removes the item with the Text value same as the string.
Remove(ListItem)Removes the specified item.
RemoveAt(integer)Removes the item at the specified index as the integer.
ClearRemoves all the items of the collection.
FindByValue(string)Returns the item whose Value is same as the string.
FindByValue(Text)Returns the item whose Text is same as the string.

Radio Button list and Check Box list


A radio button list presents a list of mutually exclusive options. A check box list presents a list of independent options. These controls contain a collection of ListItem objects that could be referred to through the Items property of the control.
Basic syntax for radio button list:
<asp:RadioButtonList ID="RadioButtonList1" 
   runat="server"
   AutoPostBack="True" 
   OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
</asp:RadioButtonList>
Basic syntax for check box list:
<asp:CheckBoxList ID="CheckBoxList1" 
   runat="server" 
   AutoPostBack="True" 
   OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged">
</asp:CheckBoxList>
Common Properties of Check Box and Radio Button Lists:
PropertyDescription
RepeatLayoutThis attribute specifies whether the table tags or the normal html flow to use while formatting the list when it is rendered. The default is Table
RepeatDirectionIt specifies the direction in which the controls to be repeated. The values available are Horizontal and Vertical. Default is Vertical
RepeatColumnsIt specifies the number of columns to use when repeating the controls; default is 0.

Bulleted lists and Numbered lists:


The bulleted list control creates bulleted lists or numbered lists. These controls contain a collection of ListItem objects that could be referred to through the Items property of the control.
Basic syntax of a bulleted list:
<asp:BulletedList ID="BulletedList1" runat="server">
</asp:BulletedList>
Common Properties of the Bulleted List:
PropertyDescription
BulletStyleThis property specifies the style and looks of the bullets, or numbers.
RepeatDirectionIt specifies the direction in which the controls to be repeated. The values available are Horizontal and Vertical. Default is Vertical
RepeatColumnsIt specifies the number of columns to use when repeating the controls; default is 0.

HyperLink Control:


The HyperLink control is like the HTML <a> element.
Basic syntax for a hyperlink control:
<asp:HyperLink ID="HyperLink1" runat="server">
   HyperLink
</asp:HyperLink>
It has the following important properties:
PropertyDescription
ImageUrlPath of the image to be displayed by the control
NavigateUrlTarget link URL
TextThe text to be displayed as the link
TargetThe window or frame which will load the linked page.

Image Control:


The image control is used for displaying images on the web page, or some alternative text, if the image is not available.
Basic syntax for an image control:
<asp:Image ID="Image1" runat="server">
It has the following important properties:
PropertyDescription
AlternateTextAlternate text to be displayed
ImageAlignAlignment options for the control
ImageUrlPath of the image to be displayed by the control


ASP.NET - Directives

ASP.Net directives are instructions to specify optional settings, such as registering a custom control and page language. These settings describe how the web forms (.aspx) or user controls (.ascx) pages are processed by the .Net framework.
The syntax for declaring a directive is:
<%@  directive_name attribute=value  [attribute=value]  %>
In this section, we will just introduce the ASP.Net directives and we will use most of these directives throughout the tutorials.

The Application Directive


The Application directive defines application-specific attributes. It is provided at the top of the global.aspx file.
The basic syntax for a sample Application directive is:
<%@ Application Language="C#" %>
The attributes of the Application directive are:
AttributesDescription
Inheritsthe name of the class from which to inherit
Descriptiontext description of the application. Parsers and compilers ignore this
Languagelanguage used in code blocks

The Assembly Directive


The Assembly directive links an assembly to the page or the application at parse time. This could appear either in the global.asax file for application-wide linking or in the page file or a user control file for linking to a page or user control.
The basic syntax for a sample Assembly directive is:
<%@ Assembly Name ="myassembly" %>
The attributes of the Assembly directive are:
AttributesDescription
Namethe name of the assembly to be linked
Srcthe path to the source file to be linked and compiled dynamically

The Control Directive


The Control directive is used with the user controls and appears in the user control (.ascx) files.
The basic syntax for a sample Control directive is:
<%@ Control Language="C#"  EnableViewState="false" %>
The attributes of the Control directive are:
AttributesDescription
AutoEventWireupthe Boolean value that enables or disables automatic association of events to handlers
ClassNamefile name for the control
Debugthe Boolean value that enables or disables compiling with debug symbols
Descriptiontext description of the control page, ignored by compiler
EnableViewStatethe Boolean value that indicates whether view state is maintained across page requests
Explicitfor VB language, tells the compiler to use Option Explicit mode
Inheritsthe class from which the control page inherits
Languagelanguage for code and script
Srcthe filename for the code-behind class
Strictfor VB language, tells the compiler to use the Option Strict mode

The Implements Directive


The Implement directive indicates that the web page, master page or user control page must implement the specified .Net framework interface.
The basic syntax for an Implements directive is:
<%@ Implements  Interface="interface_name" %>

The Import Directive


The Import directive imports a namespace into a web page, user control pate of application. If the Import directive is specified in the global.asax, then it will apply to the entire application. If it is in a page of user control page, then it would apply to that page or control.
The basic syntax for an Import directive is:
<%@ namespace="System.Drawing" %>

The Master Directive


The Master directive specifies a page file as being the mater page.
The basic syntax for a sample MasterPage directive is:
<%@ MasterPage Language="C#"  AutoEventWireup="true" 
    CodeFile="SiteMater.master.cs" Inherits="SiteMaster"  %>

The MasterType Directive


The MasterType directive assigns a class name to the Master property of a page, to make it strongly typed.
The basic syntax for a MasterType directive is:
<%@ MasterType attribute="value"[attribute="value" ...]  %>

The OutputCache Directive


The OutputCache directive controls the output caching policies of a web page or a user control. We will discuss this directive in details, in data caching.
The basic syntax for a OutputCache directive is:
<%@ OutputCache Duration="15" VaryByParam="None"  %>

The Page Directive


The Page directive defines the attributes specific to the page file for the page parser and the compiler.
The basic syntax for a Page directive is:
<%@ Page Language="C#"  AutoEventWireup="true" 
    CodeFile="Default.aspx.cs" Inherits="_Default"  Trace="true" %>
The attributes of the Page directive are:
AttributesDescription
AutoEventWireupthe Boolean value that enables or disables Page events that are being automatically bound to methods; for example, Page_Load
Bufferthe Boolean value that enables or disables HTTP response buffering
ClassNameclass name for the page
ClientTargetthe browser for which server controls should render content
CodeFilename of the code behind file
Debugthe Boolean value that enables or disables compilation with debug symbols
Descriptiontext description of the page, ignored by the parser
EnableSessionStateenables, disables or makes session state read-only
EnableViewStatethe Boolean value that enables or disables view state across page requests
ErrorPageURL for redirection if an unhandled page exception occurs
Inheritsthe name of the code behind or other class
Languageprogramming language for code
Srcfile name of the code behind class
Traceenables or disables tracing
TraceModeindicates how trace messages are to be displayed - sorted by time or category
Transactionindicates if transactions are supported
ValidateRequestthe Boolean value that indicates whether all input data is validated against a hardcoded list of values

The PreviousPageType Directive


The PreviousPageType directive assigns a class to a page, so that the page is strongly typed.
The basic syntax for a sample PreviousPagetype directive is:
<%@ PreviousPageType attribute="value"[attribute="value" ...]   %>

The Reference Directive


The Reference directive indicates that another page or user control should be compiled and linked to the current page.
The basic syntax for a sample Reference directive is:
<%@ Reference Page ="somepage.aspx" %>

The Register Directive


The Register derivative is used for registering the custom server controls and user controls.
The basic syntax for a sample Register directive is:
<%@ Register Src="~/footer.ascx" TagName="footer" 
    TagPrefix="Tfooter" %>
 
 
ASP.NET - Validation Controls 

ASP.Net validation controls validate the user input data to ensure that useless, unauthenticated or contradictory data don.t get stored.
ASP.Net provides the following validation controls:
  1. RequiredFieldValidator
  2. RangeValidator
  3. CompareValidator
  4. RegularExpressionValidator
  5. CustomValidator
  6. ValidationSummary

The BaseValidator Class:


The validation control classes inherit from the BaseValidator class and inherit its properties and methods. Therefore, it would help to take a look at the properties and the methods of this base class, which are common for all the validation controls:
MembersDescription
ControlToValidateIndicates the input control to validate.
DisplayIndicates how the error message is shown.
EnableClientScriptIndicates whether client side validation will take.
EnabledEnables or disables the validator.
ErrorMessageError string.
TextError text to be shown if validation fails.
IsValidIndicates whether the value of the control is valid.
SetFocusOnErrorIt indicates whether in case of an invalid control, the focus should switch to the related input control.
ValidationGroupThe logical group of multiple validators, where this control belongs.
Validate()This method revalidates the control and updates the IsValid property.

The RequiredFieldValidator:


The RequiredFieldValidator control ensures that the required field is not empty. It is generally tied to a text box to force input into the text box.
The syntax for the control:
<asp:RequiredFieldValidator ID="rfvcandidate" 
        runat="server" ControlToValidate ="ddlcandidate"
        ErrorMessage="Please choose a candidate" 
        InitialValue="Please choose a candidate">
</asp:RequiredFieldValidator>

The RangeValidator:


The RangeValidator control verifies that the input value falls within a predetermined range.
It has three specific properties:
PropertiesDescription
Typeit defines the type of the data; the available values are: Currency, Date, Double, Integer and String
MinimumValueit specifies the minimum value of the range
MaximumValueit specifies the maximum value of the range
The syntax for the control:
<asp:RangeValidator ID="rvclass" 
       runat="server" 
       ControlToValidate="txtclass" 
       ErrorMessage="Enter your class (6 - 12)" 
       MaximumValue="12" 
       MinimumValue="6" Type="Integer">
</asp:RangeValidator>

The CompareValidator:


The CompareValidator control compares a value in one control with a fixed value, or, a value in another control.
It has the following specific properties:
PropertiesDescription
Typeit specifies the data type
ControlToCompareit specifies the value of the input control to compare with
ValueToCompareit specifies the constant value to compare with
Operatorit specifies the comparison operator, the available values are: Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual and DataTypeCheck
The basic syntax for the control:
<asp:CompareValidator ID="CompareValidator1" 
        runat="server" 
        ErrorMessage="CompareValidator">
</asp:CompareValidator>

The RegularExpressionValidator


The RegularExpressionValidator allows validating the input text by matching against a pattern against a regular expression. The regular expression is set in the ValidationExpression property.
The following table summarizes the commonly used syntax constructs for regular expressions:
Character EscapesDescription
\bMatches a backspace
\tMatches a tab
\rMatches a carriage return
\vMatches a vertical tab
\fMatches a form feed
\nMatches a new line
\Escape character
Apart from single character match, a class of characters could be specified that can be matched, called the metacharacters.
MetacharactersDescription
.Matches any character except \n
[abcd]Matches any character in the set
[^abcd]Excludes any character in the set
[2-7a-mA-M]Matches any character specified in the range
\wMatches any alphanumeric character and underscore
\WMatches any non-word character
\sMatches whitespace characters like, space, tab, new line etc.
\SMatches any non-whitespace character
\dMatches any decimal character
\DMatches any non-decimal character
Quantifiers could be added to specify number of times a character could appear
QuantifierDescription
*Zero or more matches
+One or more matches
?Zero or one matches
{N}N matches
{N,}N or more matches
{N,M}Between N and M matches
The syntax for the control:
<asp:RegularExpressionValidator ID="string"
        runat="server"
        ErrorMessage="string"
        ValidationExpression="string"
        ValidationGroup="string">
</asp:RegularExpressionValidator>

The CustomValidator:


The CustomValidator control allows writing application specific custom validation routines for both the client side and the server side validation.
The client side validation is accomplished through the ClientValidationFunction property. The client side validation routine should be written in a scripting language, like JavaScript or VBScript, which the browser can understand.
The server side validation routine must be called from the control.s ServerValidate event handler. The server side validation routine should be written in any .Net language, like C# or VB.Net.
The basic syntax for the control
<asp:CustomValidator ID="CustomValidator1" 
       runat="server" 
       ClientValidationFunction=.cvf_func.
       ErrorMessage="CustomValidator">
</asp:CustomValidator>

The ValidationSummary Control


The ValidationSummary control does not perform any validation but shows a summary of all errors in the page. The summary displays the values of the ErrorMessage property of all validation controls that failed validation.
The following two mutually inclusive properties list out the error message:
  • ShowSummary: shows the error messages in specified format.
  • ShowMessageBox: shows the error messages in a separate window.
The syntax for the control:
<asp:ValidationSummary ID="ValidationSummary1" 
       runat="server" 
       DisplayMode = "BulletList" 
       ShowSummary = "true"
       HeaderText="Errors:" />

Validation Groups:


Complex pages have different groups of information provided in different panels. In such a situation a need for performing validation separately for separate group, might arise. This kind of situation is handled using validation groups.
To create a validation group, you should put the input controls and the validation controls into the same logical group by setting their ValidationGroup property.

Example:

The following example describes a form to be filled up by all the students of a school, divided into four houses, for electing the school president. We will be using the validation controls to validate the user input.
The form in Design view:
form in Design view
The content file code:
<form id="form1" runat="server">
<table style="width: 66%;">
<tr>
<td class="style1" colspan="3" align="center">
<asp:Label ID="lblmsg" 
           Text="President Election Form : Choose your president" 
           runat="server" />
</td>
</tr>
<tr>
<td class="style3">
Candidate:
</td>
<td class="style2">
<asp:DropDownList ID="ddlcandidate" runat="server" Width="239px">
<asp:ListItem>Please Choose a Candidate</asp:ListItem>
<asp:ListItem>M H Kabir</asp:ListItem>
<asp:ListItem>Steve Taylor</asp:ListItem>
<asp:ListItem>John Abraham</asp:ListItem>
<asp:ListItem>Venus Williams</asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator ID="rfvcandidate" 
       runat="server" ControlToValidate ="ddlcandidate"
       ErrorMessage="Please choose a candidate" 
       InitialValue="Please choose a candidate">
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style3">
House:</td>
<td class="style2">
<asp:RadioButtonList ID="rblhouse" 
      runat="server" 
      RepeatLayout="Flow">
<asp:ListItem>Red</asp:ListItem>
<asp:ListItem>Blue</asp:ListItem>
<asp:ListItem>Yellow</asp:ListItem>
<asp:ListItem>Green</asp:ListItem>
</asp:RadioButtonList>
</td>
<td>
<asp:RequiredFieldValidator ID="rfvhouse" 
       runat="server" 
       ControlToValidate="rblhouse" 
       ErrorMessage="Enter your house name">
</asp:RequiredFieldValidator>
<br />
</td>
</tr>
<tr>
<td class="style3">
Class:</td>
<td class="style2">
<asp:TextBox ID="txtclass" runat="server"></asp:TextBox>
</td>
<td>
<asp:RangeValidator ID="rvclass" 
       runat="server" ControlToValidate="txtclass" 
       ErrorMessage="Enter your class (6 - 12)" MaximumValue="12" 
       MinimumValue="6" Type="Integer">
</asp:RangeValidator>
</td>
</tr>
<tr>
<td class="style3">
Email:</td>
<td class="style2">
<asp:TextBox ID="txtemail" runat="server" Width="250px">
</asp:TextBox>
</td>
<td>
<asp:RegularExpressionValidator ID="remail" 
      runat="server" 
      ControlToValidate="txtemail" ErrorMessage="Enter your email" 
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td class="style3" align="center" colspan="3">
<asp:Button ID="btnsubmit" runat="server" onclick="btnsubmit_Click" 
style="text-align: center" Text="Submit" Width="140px" />
</td>
</tr>
</table>
<asp:ValidationSummary ID="ValidationSummary1" 
      runat="server" 
      DisplayMode ="BulletList" 
      ShowSummary ="true"
      HeaderText="Errors:" />
</form>
The code behind the submit button:
protected void btnsubmit_Click(object sender, EventArgs e)
{
   if (Page.IsValid)
   {
      lblmsg.Text = "Thank You";
   }
   else
   {
      lblmsg.Text = "Fill up all the fields";
   }
}
 
 
ASP.NET - Managing State 


HTTP ( Hyper Text Transfer Protocol) is a stateless protocol. When the client disconnects from the server, the ASP.Net engine discards the page objects. This way each web application can scale up to serve numerous requests simultaneously without running out of server memory.
However, there need to be some technique to store the information between requests and to retrieve it when required. This information i.e., the current value of all the controls and variables for the current user in the current session is called the State.
ASP.Net manages four types of state:
  1. View State
  2. Control State
  3. Session State
  4. Application State

View State:


The View State is the state of the page and all its controls. It is automatically maintained across posts by the ASP.Net framework.
When a page is sent back to the client, the changes in the properties of the page and its controls are determined and stored in the value of a hidden input field named _VIEWSTATE. When the page is again post back the _VIEWSTATE field is sent to the server with the HTTP request.
The view state could be enabled or disabled for:
  • The entire application - by setting the EnableViewState property in the <pages> section of web.config file
  • A page - by setting the EnableViewState attribute of the Page directive, as <%@ Page Language="C#" EnableViewState="false" %>
  • A control - by setting the Control.EnableViewState property.
It is implemented using a view state object defined by the StateBag class which defines a collection of view state items. The state bag is a data structure containing attribute/value pairs, stored as strings associated with objects.
The StateBag class has the following properties:
PropertiesDescription
Item(name)The value of the view state item with the specified name. This is the default property of the StateBag class
CountThe number of items in the view state collection
KeysCollection of keys for all the items in the collection
ValuesCollection of values for all the items in the collection
The StateBag class has the following methods
MethodsDescription
Add(name, value)Adds an item to the view state collection and existing item is updated
ClearRemoves all the items from the collection
Equals(Object)Determines whether the specified object is equal to the current object.
FinalizeAllows it to free resources and perform other cleanup operations.
GetEnumeratorReturns an enumerator that iterates over all the key/value pairs of the StateItem objects stored in the StateBag object.
GetTypeGets the Type of the current instance.
IsItemDirtyChecks a StateItem object stored in the StateBag object to evaluate whether it has been modified.
Remove(name)Removes the specified item.
SetDirtySets the state of the StateBag object as well as the Dirty property of each of the StateItem objects contained by it.
SetItemDirtySets the Dirty property for the specified StateItem object in the StateBag object.
ToStringReturns a String representing the state bag object.

Example:

The following example demonstrates the concept of storing view state. Let us keep a counter, which is incremented each time the page is post back by clicking a button on the page. A label control shows the value in the counter.
The markup file:
<%@ Page Language="C#" 
         AutoEventWireup="true" 
         CodeBehind="Default.aspx.cs" 
         Inherits="statedemo._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h3>View State demo</h3>
    Page Counter:
    <asp:Label ID="lblCounter" runat="server" />
    <asp:Button ID="btnIncrement" runat="server" 
                Text="Add Count" 
                onclick="btnIncrement_Click" />
    </div>
    </form>
</body>
</html>
The code behind file for the example is shown here:
public partial class _Default : System.Web.UI.Page
{
        public int counter
        {
            get
            {
                if (ViewState["pcounter"] != null)
                {
                    return ((int)ViewState["pcounter"]);
                }
                else
                {
                    return 0;
                }
            }
            set
            {
                ViewState["pcounter"] = value;
            }
        }
        
        protected void Page_Load(object sender, EventArgs e)
        {
            lblCounter.Text = counter.ToString();
            counter++;
        }
}
This would produce following result:
View State Demo

Control State:


Control state cannot be modified, accessed directly or disabled.

Session State:


When a user connects to an ASP.Net website, a new session object is created. When session state is turned on, a new session state object is created for each new request. This session state object becomes part of the context and it is available through the page.
Session state is generally used for storing application data like inventory or supplier list, or a customer record or shopping cart. It can also keep information about the user and his preference and keep track of pending operations.
Sessions are identified and tracked with a 120-bit SessionID, which is passed from client to server and back as cookie or a modified URL. The SessionID is globally unique and random.
The session state object is created from the HttpSessionState class, which defines a collection of session state items.
The HttpSessionState class has the following properties:
PropertiesDescription
SessionIDThe unique session identifier
Item(name)The value of the session state item with the specified name. This is the default property of the HttpSessionState class
CountThe number of items in the session state collection
TimeOutGets and sets the amount of time, in minutes, allowed between requests before the session-state provider terminates the session.
The HttpSessionState class has the following methods:
MethodsDescription
Add(name, value)Adds an item to the session state collection
ClearRemoves all the items from session state collection
Remove(name)Removes the specified item from the session state collection
RemoveAllRemoves all keys and values from the session-state collection.
RemoveAtDeletes an item at a specified index from the session-state collection.
The session state object is a name-value pair, to store and retrieve some information from the session state object the following code could be used:
void StoreSessionInfo()
{
 String fromuser = TextBox1.Text;
 Session["fromuser"] = fromuser;
}
void RetrieveSessionInfo()
{
 String fromuser = Session["fromuser"];
 Label1.Text = fromuser;
}
The above code stores only strings in the Session dictionary object, however, it can store all the primitive data types and arrays composed of primitive data types, as well as the DataSet, DataTable, HashTable, and Image objects, as well as any user defined class that inherits from the ISerializable object.

Example:

The following example demonstrates the concept of storing session state. There are two buttons on the page, a text box to enter string and a label to display the text stored from last session.
The mark up file:
<%@ Page Language="C#" 
    AutoEventWireup="true"  
    CodeFile="Default.aspx.cs" 
    Inherits="_Default"  %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
        &nbsp; &nbsp; &nbsp;
 <table style="width: 568px; height: 103px">
 <tr>
 <td style="width: 209px">
 <asp:Label ID="lblstr" runat="server" 
          Text="Enter a String" Width="94px">
 </asp:Label>
 </td>
 <td style="width: 317px">
 <asp:TextBox ID="txtstr" runat="server" Width="227px">
 </asp:TextBox>
 </td>
 </tr>
 <tr>
 <td style="width: 209px"></td>
 <td style="width: 317px"></td>
 </tr>
 <tr>
 <td style="width: 209px">
 <asp:Button ID="btnnrm" runat="server" 
          Text="No action button" Width="128px" />
 </td>
 <td style="width: 317px">
 <asp:Button ID="btnstr" runat="server" 
          OnClick="btnstr_Click" Text="Submit the String" />
 </td> 
 </tr>
 <tr>
 <td style="width: 209px">
 </td>
 <td style="width: 317px">
 </td>  
 </tr>
 <tr>
 <td style="width: 209px">
 <asp:Label ID="lblsession" runat="server" 
          Width="231px">
 </asp:Label>
 </td>
 <td style="width: 317px">
 </td>
 </tr>
 <tr>
 <td style="width: 209px">
 <asp:Label ID="lblshstr" runat="server">
 </asp:Label>
 </td>
 <td style="width: 317px">
 </td>
 </tr>
 </table>
  </div>
  </form>
</body>
</html>
It should look like the following in design view:
session design view
The code behind file is given here:
public partial class _Default : System.Web.UI.Page 
{
    String mystr;
    protected void Page_Load(object sender, EventArgs e)
    {
        this.lblshstr.Text = this.mystr;
        this.lblsession.Text = (String)this.Session["str"];
    }
    protected void btnstr_Click(object sender, EventArgs e)
    {
        this.mystr = this.txtstr.Text;
        this.Session["str"] = this.txtstr.Text;
        this.lblshstr.Text = this.mystr;

        this.lblsession.Text = (String)this.Session["str"];
    }
}
Run the file and observe how it works:
session run view

Application State


An ASP.Net application is the collection of all web pages, code and other files within a single virtual directory on a web server. When information is stored in application state, it is available to all the users.
To provide for the use of application state, ASP.Net creates an application state object for each application from the HTTPApplicationState class and stores this object in server memory. This object is represented by class file global.asax.
Application State is mostly used to store hit counters and other statistical data, global application data like tax rate, discount rate etc and to keep track of users visiting the site.
The HttpApplicationState class has the following properties:
PropertiesDescription
Item(name)The value of the application state item with the specified name. This is the default property of the HttpApplicationState class.
CountThe number of items in the application state collection.
The HttpApplicationState class has the following methods:
MethodsDescription
Add(name, value)Adds an item to the application state collection .
ClearRemoves all the items from the application state collection.
Remove(name)Removes the specified item from the application state collection.
RemoveAllRemoves all objects from an HttpApplicationState collection.
RemoveAtRemoves an HttpApplicationState object from a collection by index.
Lock()Locks the application state collection so only the current user can access it.
Unlock()Unlocks the application state collection so all the users can access it.
Application state data is generally maintained by writing handlers for the events:
  • Application_Start
  • Application_End
  • Application_Error
  • Session_Start
  • Session_End
The following code snippet shows the basic syntax for storing application state information:
Void Application_Start(object sender, EventArgs e)
{
  Application["startMessage"] = "The application has started.";
}
Void Application_End(object sender, EventArgs e)
{
  Application["endtMessage"] = "The application has ended.";
}



ASP.NET - 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" 
                     runat="server" 
                     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:
PropertyDescription
AccessKeyPressing this key with the Alt key moves focus to the control
AttributesIt'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.
ControlsCollection 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.
EventsGets 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.
HeightHeight 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.
ViewStateModeGets 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:
MethodDescription
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.

Example:


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: " + 
                       TreeView1.SelectedNode.Text;
    TreeNodeCollection childnodes = 
                       TreeView1.SelectedNode.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
ASP.NET - Server Side

We have studied the page life cycle and how a page contains various controls. The page itself is instantiated as a control object. All web forms are basically instances of the ASP.Net Page class. The page class has the following extremely useful properties that correspond to intrinsic objects like:
  • Session.
  • Application
  • Cache
  • Request
  • Response
  • Server
  • User
  • Trace
We will discuss each of these objects in due time. In this tutorial we will explore the Server object, the Request object and the Response object.

The Server Object:


The Server object in Asp.Net is an instance of the System.Web.HttpServerUtility class. The HttpServerUtility class provides numerous properties and methods to perform various jobs.

Properties and Methods of the Server object:

The methods and properties of the HttpServerUtility class are exposed through the intrinsic Server object provided by ASP.NET.
The following table provides a list of the properties:
PropertyDescription
MachineNameName of server's computer
ScriptTimeOutGets and sets the request time-out value in seconds.
The following table provides a list of some important methods:
MethodDescription
CreateObject(String)Creates an instance of the COM object identified by its ProgID (Programmatic ID)
CreateObject(Type)Creates an instance of the COM object identified by its Type
Equals(Object)Determines whether the specified Object is equal to the current Object
Execute(String)Executes the handler for the specified virtual path in the context of the current request.
Execute(String, Boolean)Executes the handler for the specified virtual path in the context of the current request and specifies whether to clear the QueryString and Form collections
GetLastErrorReturns the previous exception.
GetTypeGets the Type of the current instance.
HtmlEncodeChanges an ordinary string into a string with legal HTML characters.
HtmlDecodeConverts an Html string into an ordinary string
ToStringReturns a String that represents the current Object
Transfer(String)For the current request, terminates execution of the current page and starts execution of a new page by using the specified URL path of the page.
UrlDecodeConverts an URL string into an ordinary string
UrlEncodeTokenWorks same as UrlEncode, but on a byte array that contains Base64-encoded data
UrlDecodeTokenWorks same as UrlDecode, but on a byte array that contains Base64-encoded data
MapPathReturn the physical path that corresponds to a specified virtual file path on the server
TransferTransfers execution to another web page in the current application

The Request Object:


The request object is an instance of the System.Web.HttpRequest class. It represents the values and properties of the HTTP request that makes the page loading into the browser.
The information presented by this object is wrapped up by the higher level abstractions (the web control model), however, this object helps in checking some information like the client browser and cookies.

Properties and Methods of the Request Object:

The following table provides some noteworthy properties of the Request object:
PropertyDescription
AcceptTypesGets a string array of client-supported MIME accept types.
ApplicationPathGets the ASP.NET application's virtual application root path on the server.
BrowserGets or sets information about the requesting client's browser capabilities.
ContentEncodingGets or sets the character set of the entity-body.
ContentLengthSpecifies the length, in bytes, of content sent by the client.
ContentTypeGets or sets the MIME content type of the incoming request.
CookiesGets a collection of cookies sent by the client.
FilePathGets the virtual path of the current request.
FilesGets the collection of files uploaded by the client, in multipart MIME format.
FormGets a collection of form variables.
HeadersGets a collection of HTTP headers.
HttpMethodGets the HTTP data transfer method (such as GET, POST, or HEAD) used by the client.
InputStreamGets the contents of the incoming HTTP entity body.
IsSecureConnectionGets a value indicating whether the HTTP connection uses secure sockets (that is, HTTPS).
QueryStringGets the collection of HTTP query string variables.
RawUrlGets the raw URL of the current request.
RequestTypeGets or sets the HTTP data transfer method (GET or POST) used by the client.
ServerVariablesGets a collection of Web server variables.
TotalBytesGets the number of bytes in the current input stream.
UrlGets information about the URL of the current request.
UrlReferrerGets information about the URL of the client's previous request that linked to the current URL.
UserAgentGets the raw user agent string of the client browser.
UserHostAddressGets the IP host address of the remote client.
UserHostNameGets the DNS name of the remote client.
UserLanguagesGets a sorted string array of client language preferences.
The following table provides a list of some important methods:
MethodDescription
BinaryReadPerforms a binary read of a specified number of bytes from the current input stream.
Equals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
GetTypeGets the Type of the current instance.
MapImageCoordinatesMaps an incoming image-field form parameter to appropriate x-coordinate and y-coordinate values.
MapPath(String)Maps the specified virtual path to a physical path.
SaveAsSaves an HTTP request to disk.
ToStringReturns a String that represents the current Object
ValidateInputCauses validation to occur for the collections accessed through the Cookies, Form, and QueryString properties.

The Response Object:


The Response object represents the server's response to the client request. It is an instance of the System.Web.HttpResponse class.
In ASP.Net, the Response object does not play a vital role in sending HTML text to the client, because the server-side controls have nested, object oriented methods for rendering themselves.
However, the HttpResponse object still provides some important functionalities, like the cookie feature and the Redirect() method. The Response.Redirect() method allows transferring the user to another page, inside as well as outside the application. It requires a round trip.

Properties and Methods of the Response Object:

The following table provides some noteworthy properties of the Response object:
PropertyDescription
BufferGets or sets a value indicating whether to buffer output and send it after the complete response is finished processing.
BufferOutputGets or sets a value indicating whether to buffer output and send it after the complete page is finished processing.
CharsetGets or sets the HTTP character set of the output stream.
ContentEncodingGets or sets the HTTP character set of the output stream.
ContentTypeGets or sets the HTTP MIME type of the output stream.
CookiesGets the response cookie collection.
ExpiresGets or sets the number of minutes before a page cached on a browser expires.
ExpiresAbsoluteGets or sets the absolute date and time at which to remove cached information from the cache
HeaderEncodingGets or sets an Encoding object that represents the encoding for the current header output stream.
HeadersGets the collection of response headers.
IsClientConnectedGets a value indicating whether the client is still connected to the server.
OutputEnables output of text to the outgoing HTTP response stream.
OutputStreamEnables binary output to the outgoing HTTP content body.
RedirectLocationGets or sets the value of the Http Location header.
StatusSets the Status line that is returned to the client.
StatusCodeGets or sets the HTTP status code of the output returned to the client.
StatusDescriptionGets or sets the HTTP status string of the output returned to the client.
SubStatusCodeGets or sets a value qualifying the status code of the response.
SuppressContentGets or sets a value indicating whether to send HTTP content to the client.
The following table provides a list of some important methods:
MethodDescription
AddHeaderAdds an HTTP header to the output stream. AddHeader is provided for compatibility with earlier versions of ASP.
AppendCookieInfrastructure. Adds an HTTP cookie to the intrinsic cookie collection.
AppendHeaderAdds an HTTP header to the output stream.
AppendToLogAdds custom log information to the Internet Information Services (IIS) log file.
BinaryWriteWrites a string of binary characters to the HTTP output stream.
ClearContentClears all content output from the buffer stream.
CloseCloses the socket connection to a client.
EndSends all currently buffered output to the client, stops execution of the page, and raises the EndRequest event.
Equals(Object)Determines whether the specified Object is equal to the current Object
FlushSends all currently buffered output to the client.
GetTypeGets the Type of the current instance.
PicsAppends a HTTP PICS-Label header to the output stream.
Redirect(String)Redirects a request to a new URL and specifies the new URL.
Redirect(String, Boolean)Redirects a client to a new URL. Specifies the new URL and whether execution of the current page should terminate.
SetCookieUpdates an existing cookie in the cookie collection.
ToStringReturns a String that represents the current Object.
TransmitFile(String)Writes the specified file directly to an HTTP response output stream, without buffering it in memory.
Write(Char)Writes a character to an HTTP response output stream.
Write(Object)Writes an Object to an HTTP response stream.
Write(String)Writes a string to an HTTP response output stream.
WriteFile(String)Writes the contents of the specified file directly to an HTTP response output stream as a file block.
WriteFile(String, Boolean)Writes the contents of the specified file directly to an HTTP response output stream as a memory block.

Example:


The following simple example has a text box control where the user can enter name, a button to send the information to the server and a label control to display the URL of the client computer.
The content file:
<%@ Page Language="C#" AutoEventWireup="true" 
                       CodeBehind="Default.aspx.cs" 
                       Inherits="server_side._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Enter your name:<br />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" 
                    OnClick="Button1_Click" Text="Submit" />
        <br />
        <asp:Label ID="Label1" runat="server"/>

    </div>
    </form>
</body>
</html>
The code behind for Button1_Click:
protected void Button1_Click(object sender, EventArgs e)
{
   if (!String.IsNullOrEmpty(TextBox1.Text))
   {
       // Access the HttpServerUtility methods through
       // the intrinsic Server object.
       Label1.Text = "Welcome, " +
       Server.HtmlEncode(TextBox1.Text) +
       ".<br/> The url is " +
       Server.UrlEncode(Request.Url.ToString());
    }

 }
Run the page to see the following result
ASP.NET Server Side

 ASP.NET - Database Access

ASP.Net allows the following sources of data to be accessed and used:
  • Databases (e.g., Access, SQL Server, Oracle, MySQL)
  • XML documents
  • Business Objects
  • Flat files
ASP.Net hides the complex processes of data access and provides much higher level of classes and objects through which data is accessed easily. These classes hide all complex coding for connection, data retrieving, data querying and data manipulation.
ADO.Net is the technology that provides the bridge between various ASP.Net control objects and the backend data source. We will come to ADO.Net in due time. In this tutorial, we will look at data access and working with the data without going into the details of its inner workings.

Retrieve and display data:


It takes two types of data controls to retrieve and display data in ASP.Net:
  1. A data source control . it manages the connection to the data, selection of data and other jobs like paging and caching of data etc.
  2. A data view control . it binds and displays the data and allows data manipulation.
We will discuss the data binding and data source controls in details later. In this section, we will use a SqlDataSource control to access data and a GridView control to display and manipulate data.
We will also use an Access database, which has details about .Net books available in the market. Name of our database is ASPDotNetStepByStep.mdb and we will use the data table DotNetReferences.
The table has the following columns: ID, Title, AuthorFirstName, AuthorLastName, Topic, and Publisher.
Here is a snapshot of the data table:
Data Table
Let us directly move to action, take the following steps:
(1) Create a web site and add a SqlDataSourceControl on the web form.
SqlDataSourceControl
(2) Click on the Configure Data Source Link.
Configure Data Source
(3) Click on the New Connection button to establish connection with a database.
Connection with a database
(4) Once the connection is set up, you may save it for further use. At the next step, you are asked to configure the select statement:
Select statement
(5) Select the columns and click next to complete the steps. Observe the WHERE, ORDER BY, AND the Advanced. Buttons. These buttons allow you to provide the where clause, order by clause and specify the insert, update and delete commands of SQL respectively. This way, you can manipulate the data.
(6) Add a GridView control on the form. Choose the data source and format the control using AutoFormat option.
AutoFormat
(7) After this the formatted GridView control displays the column headings, and the application is ready to run.
GridView control
(8) Finally Run the application
Database Result
The content file code:
<%@ Page Language="C#" 
         AutoEventWireup="true" 
         CodeBehind="dataaccess.aspx.cs" 
         Inherits="datacaching.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:SqlDataSource ID="SqlDataSource1" 
   runat="server" 
   ConnectionString=
   "<%$ ConnectionStrings:ASPDotNetStepByStepConnectionString%>" 
   ProviderName=
   "<%$ ConnectionStrings:
        ASPDotNetStepByStepConnectionString.ProviderName %>" 
   SelectCommand="SELECT [Title], [AuthorLastName], 
                         [AuthorFirstName], [Topic] 
                  FROM [DotNetReferences]">
</asp:SqlDataSource>
<asp:GridView ID="GridView1" 
   runat="server" 
   AutoGenerateColumns="False" 
   CellPadding="4" 
   DataSourceID="SqlDataSource1" 
   ForeColor="#333333" 
   GridLines="None">
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
<asp:BoundField DataField="Title" HeaderText="Title" 
SortExpression="Title" />
<asp:BoundField DataField="AuthorLastName" 
HeaderText="AuthorLastName" 
SortExpression="AuthorLastName" />
<asp:BoundField DataField="AuthorFirstName" 
HeaderText="AuthorFirstName" 
SortExpression="AuthorFirstName" />
<asp:BoundField DataField="Topic" 
HeaderText="Topic" SortExpression="Topic" />
</Columns>
<FooterStyle BackColor="#5D7B9D" 
Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" 
ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" 
Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True"  
ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
</div>
</form>
</body>
</html>


ASP.NET - File Uploading

ASP.Net has two controls that allow the users to upload files to the web server. Once the server receives the posted file data, the application can save it, check it or ignore it. The following controls allow the file uploading:
  • HtmlInputFile - an HTML server control
  • FileUpload - and ASP.Net web control
Both the controls allow file uploading, but the FileUpload control automatically sets the encoding of the form, whereas the HtmlInputFile does not do so.
In this tutorial, we will use the FileUpload control. The FileUpload control allows the user to browse for and select the file to be uploaded, providing a Browse button and a text box for entering the filename.
Once, the user has entered the filename in the text box, by typing the name or browsing, the SaveAs method of the FileUpload control can be called to save the file to the disk.
The basic syntax for using the FileUpload is:
<asp:FileUpload ID= "Uploader" runat = "server" />
The FileUpload class is derived from the WebControl class, and inherits all its members. Apart from those, the FileUpload class has the following read-only properties:
PropertiesDescription
FileBytesReturns an array of the bytes in a file to be uploaded..
FileContentReturns the stream object pointing to the file to be uploaded.
FileNameReturns the name of the file to be uploaded.
HasFileSpecifies whether the control has a file to upload.
PostedFileReturns a reference to the uploaded file.
The posted file is encapsulated in an object of type HttpPostedFile, which could be accessed through the PostedFile property of the FileUpload class.
The HttpPostedFile class has the following important properties, which are much used:
PropertiesDescription
ContentLengthReturns the size of the uploaded file in bytes.
ContentTypeReturns the MIME type of the uploaded file
FileNameReturns the full filename.
InputStreamReturns a stream object pointing to the uploaded file.

Example:

The following example demonstrates the FileUpload control and its properties. The form has a FileUpload control along with a save button and a label control for displaying the file name, file type and file length.
In the design view, the form looks like:
File Upload
The content file:
<body>
<form id="form1" runat="server">
<div>
<h3> File Upload:</h3>
<br />
   <asp:FileUpload ID="FileUpload1" runat="server" />
   <br /><br />
   <asp:Button ID="btnsave" runat="server" 
               onclick="btnsave_Click" Text="Save" 
               Width="85px" />
   <br /><br />
   <asp:Label ID="lblmessage" runat="server" />
</div>
</form>
</body>
The code behind the save button:
protected void btnsave_Click(object sender, EventArgs e)
{
   StringBuilder sb = new StringBuilder();
   if (FileUpload1.HasFile)
   {
      try
      {
      sb.AppendFormat(" Uploading file: {0}", 
                                  FileUpload1.FileName);
      //saving the file
      FileUpload1.SaveAs("<c:\\SaveDirectory>" + 
                                  FileUpload1.FileName);
      //Showing the file information
      sb.AppendFormat("<br/> Save As: {0}", 
                         FileUpload1.PostedFile.FileName);
      sb.AppendFormat("<br/> File type: {0}",   
                         FileUpload1.PostedFile.ContentType);
      sb.AppendFormat("<br/> File length: {0}", 
                         FileUpload1.PostedFile.ContentLength);
      sb.AppendFormat("<br/> File name: {0}", 
                         FileUpload1.PostedFile.FileName);
      }
      catch (Exception ex)
      {
      sb.Append("<br/> Error <br/>");
      sb.AppendFormat("Unable to save file <br/> {0}", 
                         ex.Message);
      }
   }
   else
   {
      lblmessage.Text = sb.ToString();
   }
}
Note the following:
  • The StringBuilder class is derived from System.IO namespace, so it should be included.
  • The try and catch blocks are used for catching errors, and display the error message.




ASP.NET - Ad Rotator

The AdRotator control randomly selects banner graphics from a list, which is specified in an external XML schedule file. This external XML schedule file is called the advertisement file.
The AdRotator control allows you to specify the advertisement file and the type of window that the link should follow in AdvertisementFile and Target property respectively.
The basic syntax of adding an AdRotator is as follows:
<asp:AdRotator  runat = "server" 
                AdvertisementFile = "adfile.xml"  
                Target = "_blank" />
Before going into details of the AdRotator control and its properties, let us look into the construction of the advertisement file.

The Advertisement File:


The advertisement file is an XML file, which contains the information about the advertisements to be displayed.
Extensible Markup Language (XML) is a W3C standard for text document markup. It is a text-based markup language that enables you to store data in a structured format by using meaningful tags. The term 'extensible' implies that you can extend you ability to describe a document by defining meaningful tags for your application.
XML is not a language in itself, like HTML but, a set of rules for creating new markup languages. It is a meta-markup language. It allows developers to create custom tag sets for special uses. It structures, stores and transport information.
Following is an example of XML file:
<BOOK>
<NAME> Learn XML </NAME>
<AUTHOR> Samuel Peterson </AUTHOR>
<PUBLISHER> NSS Publications </PUBLISHER>
<PRICE> $30.00</PRICE>
</BOOK>
Like all XML files, the advertisement file needs to be a structured text file with well-defined tags delineating the data. There are the following standard XML elements that are commonly used in the advertisement file:
ElementDescription
AdvertisementsEncloses the advertisement file
AdDelineates separate ad
ImageUrlThe image that will be displayed
NavigateUrlThe link that will be followed when the user clicks the ad
AlternateTextThe text that will be displayed instead of the picture if it cannot be displayed
KeywordKeyword identifying a group of advertisements. This is used for filtering
ImpressionsThe number indicating how often an advertisement will appear
HeightHeight of the image to be displayed
WidthWidth of the image to be displayed
Apart from these tags, customs tags with custom attributes could also be included. The following code illustrates an advertisement file ads.xml:
<Advertisements>
<Ad>
<ImageUrl>rose1.jpg</ImageUrl>
<NavigateUrl>http://www.1800flowers.com</NavigateUrl>
<AlternateText>
   Order flowers, roses, gifts and more
</AlternateText>
<Impressions>20</Impressions>
<Keyword>flowers</Keyword>
</Ad>

<Ad>
<ImageUrl>rose2.jpg</ImageUrl>
<NavigateUrl>http://www.babybouquets.com.au</NavigateUrl>
<AlternateText>Order roses and flowers</AlternateText>
<Impressions>20</Impressions>
<Keyword>gifts</Keyword>
</Ad>

<Ad>
<ImageUrl>rose3.jpg</ImageUrl>
<NavigateUrl>http://www.flowers2moscow.com</NavigateUrl>
<AlternateText>Send flowers to Russia</AlternateText>
<Impressions>20</Impressions>
<Keyword>russia</Keyword>
</Ad>

<Ad>
<ImageUrl>rose4.jpg</ImageUrl>
<NavigateUrl>http://www.edibleblooms.com</NavigateUrl>
<AlternateText>Edible Blooms</AlternateText>
<Impressions>20</Impressions>
<Keyword>gifts</Keyword>
</Ad>
</Advertisements>

Properties and events of the AdRotator Class:


The AdRotator class is derived from the WebControl class and inherits its properties. Apart from those the AdRotator class has the following properties:
PropertiesDescription
AdvertisementFileThe path to the advertisement file.
AlternateTextFeildThe element name of the field where alternate text is provided; default value is AlternateText.
DataMemberThe name of the specific list of data to be bound when advertisement file is not used.
DataSourceControl from where it would retrieve data.
DataSourceIDId of the control from where it would retrieve data.
FontSpecifies the font properties associated with the advertisement banner control.
ImageUrlFieldThe element name of the field where the URL for the image is provided; default value is ImageUrl.
KeywordFilterFor displaying the keyword based ads only.
NavigateUrlFieldThe element name of the field where the URL to navigate to is provided; default value is NavigateUrl.
TargetThe browser window or frame that displays the content of the page linked.
UniqueIDObtains the unique, hierarchically qualified identifier for the AdRotator control.
Following are the important events of the AdRotator Class:
EventsDescription
AdCreatedIt is raised once per round trip to the server after creation of the control, but before the page is rendered
DataBindingOccurs when the server control binds to a data source.
DataBoundOccurs after the server control binds to a data source.
DisposedOccurs when a server control is released from memory, which is the last stage of the server control lifecycle when an ASP.NET page is requested
InitOccurs when the server control is initialized, which is the first step in its lifecycle.
LoadOccurs when the server control is loaded into the Page object.
PreRenderOccurs after the Control object is loaded but prior to rendering.
UnloadOccurs when the server control is unloaded from memory.

Working with the AdRotator Control


Create a new web page and place an AdRotator control on it.
<form id="form1" runat="server">
<div>
   <asp:AdRotator ID="AdRotator1" 
                runat="server" AdvertisementFile ="~/ads.xml"
                onadcreated="AdRotator1_AdCreated" />
  
</div>
</form>
The ads.xml file and the image files should be located in the root directory of the web site.
Try to run the above application an dobserve that each time the page is reloaded, the ad is changed.


ASP.NET - Calendars

The calendar control is a functionally rich web control, which provides the following capabilities:
  • Displaying one month at a time
  • Selecting a day, a week or a month
  • Selecting a range of days
  • Moving from month to month
  • Controlling the display of the days programmatically
The basic syntax for adding a calendar control is:
<asp:Calender ID = "Calendar1" runat = "server"></asp:Calender>

Properties and Events of the Calendar Control


The calendar control has many properties and events, using which you can customize the actions and display of the control. The following table provides some important properties of the Calendar control:
PropertiesDescription
CaptionGets or sets the caption for the calendar control.
CaptionAlignGets or sets the alignment for the caption.
CellPaddingGets or sets the number of space between the data and the cell.s border.
CellSpacingGets or sets the space between cells.
DayHeaderStyleGets the style properties for the section that displays the day of the week.
DayNameFormatGets or sets format of days of the week.
DayStyleGets the style properties for the days in the displayed month.
FirstDayOfWeekGets or sets the day of week to display in the first column.
NextMonthTextGets or sets the text for next month navigation control; default value is >
NextPrevFormatGets or sets the format of the next and previous month navigation control.
OtherMonthDayStyleGets the style properties for the days on the Calendar control that are not in the displayed month.
PrevMonthTextGets or sets the text for previous month navigation control; default value is <
SelectedDateGets or sets the selected date.
SelectedDatesGets a collection of DateTime objects representing the selected dates.
SelectedDayStyleGets the style properties for the selected dates.
SelectionModeGets or sets the selection mode that specifies whether the user can select a single day, a week or an entire month.
SelectMonthTextGets or sets the text for the month selection element in the selector column.
SelectorStyleGets the style properties for the week and month selector column.
SelectWeekTextGets or sets the text displayed for the week selection element in the selector column.
ShowDayHeaderGets or sets the value indicating whether the heading for the days of the week is displayed.
ShowGridLinesGets or sets the value indicating whether the gridlines would be shown.
ShowNextPrevMonthGets or sets a value indicating whether next and previous month navigation elements are shown in the title section.
ShowTitleGets or sets a value indicating whether the title section is displayed.
TitleFormatGets or sets the format for the title section.
TitlestyleGet the style properties of the title heading for the Calendar control.
TodayDayStyleGets the style properties for today's date on the Calendar control.
TodaysDateGets or sets the value for today.s date.
UseAccessibleHeaderGets or sets a value that indicates whether to render the table header <th> HTML element for the day headers instead of the table data <td> HTML element.
VisibleDateGets or sets the date that specifies the month to display.
WeekendDayStyleGets the style properties for the weekend dates on the Calendar control.
The Calendar control has the following three most important events that allow the developers to program the calendar control. These are:
EventsDescription
SelectionChangedIt is raised when a day, a week or an entire month is selected
DayRenderIt is raised when each data cell of the calendar control is rendered.
VisibleMonthChangedIt is raised when user changes a month

Working with the Calendar Control


Putting a bare-bone calendar control without any code behind file provides a workable calendar to a site, which shows the month and days of the year. It also allows navigating to next and previous months.
Calendar
Calendar controls allow the users to select a single day, a week or an entire month. This is done by using the SelectionMode property. This property has the following values:
PropertiesDescription
DayTo select a single day
DayWeekTo select a single day or an entire week
DayWeekMonthTo select a single day, a week or an entire month
NoneNothing can be selected
The syntax for selecting days:
<asp:Calender ID = "Calendar1" 
                 runat = "server"
                 SelectionMode="DayWeekMonth">
</asp:Calender>
When the selection mode is set to the value DayWeekMonth, an extra column with the > symbol appears for selecting the week and a >> symbol appears to the left of the days' name for selecting the month.
Calendar2

Example:

The following example demonstrates selecting a date and displays the date in a label:
The content file:
<%@ Page Language="C#" 
         AutoEventWireup="true" 
         CodeBehind="Default.aspx.cs" 
         Inherits="calendardemo._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h3> Your Birthday:</h3>
        <asp:Calendar ID="Calendar1" 
             runat="server" 
             SelectionMode="DayWeekMonth"
             onselectionchanged="Calendar1_SelectionChanged">
        </asp:Calendar>
    </div>
    <p>Todays date is: 
        <asp:Label ID="lblday" runat="server"></asp:Label>
    </p>
    <p>Your Birday is: 
        <asp:Label ID="lblbday" runat="server"></asp:Label>
    </p>
    </form>
</body>
</html>
The event handler for the event SelectionChanged:
protected void Calendar1_SelectionChanged(object sender, 
                                          EventArgs e)
{
    lblday.Text = Calendar1.TodaysDate.ToShortDateString();
    lblbday.Text = Calendar1.SelectedDate.ToShortDateString();
}
When the file run should produce the following output:
Calendar3

Contact Form

Name

Email *

Message *