0% found this document useful (0 votes)
59 views

ASP .Net Notes

The document outlines the ASP.NET life cycle, which is divided into the Application Life Cycle and the Page Life Cycle, detailing the stages involved in processing requests and rendering pages. It also covers ASP.NET directives that provide settings for web forms and user controls, as well as the Provider Model that enhances application architecture through customizable components. Additionally, it discusses ASP.NET server controls, the global.asax application file for handling system-level events, and the various events associated with it.

Uploaded by

sahilmahara23
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views

ASP .Net Notes

The document outlines the ASP.NET life cycle, which is divided into the Application Life Cycle and the Page Life Cycle, detailing the stages involved in processing requests and rendering pages. It also covers ASP.NET directives that provide settings for web forms and user controls, as well as the Provider Model that enhances application architecture through customizable components. Additionally, it discusses ASP.NET server controls, the global.asax application file for handling system-level events, and the various events associated with it.

Uploaded by

sahilmahara23
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Asp .

Net
The ASP.NET life cycle could be divided into two groups:

 Application Life Cycle


 Page Life Cycle

1. ASP.NET Application Life Cycle

The application life cycle has the following stages:


 User makes a request for accessing application resource, a page. Browser sends
this request to the web server.
 A unified pipeline receives the first request and the following events take
place:
o An object of the class ApplicationManager is created.
o An object of the class HostingEnvironment is created to provide
information regarding the resources.
o Top level items in the application are compiled.
 Response objects are created. The application objects such as HttpContext,
HttpRequest and HttpResponse are created and initialized.
 An instance of the HttpApplication object is created and assigned to the
request.
 The request is processed by the HttpApplication class. Different events are
raised by this class for processing the request.

2. ASP.NET Page Life Cycle

When a page is requested, it is loaded into the server memory, processed, and sent to the
browser. Then it is unloaded from the memory. At each of these steps, methods and events
are available, which could be overridden according to the need of the application. In other
words, you can write your own code to override the default code.
The Page class creates a hierarchical tree of all the controls on the page. All the components
on the page, except the directives, are part of this control tree. You can see the control tree by
adding trace= "true" to the page directive. We will cover page directives and tracing under
'directives' and 'event handling'.
The page life cycle phases are:

 Initialization
 Instantiation of the controls on the page
 Restoration and maintenance of the state
 Execution of the event handler codes
 Page rendering
Understanding the page cycle helps in writing codes for making some specific thing happen
at any stage of the page life cycle. It also helps in writing custom controls and initializing
them at right time, populate their properties with view-state data and run control behavior
code.
Following are the different stages of an ASP.NET page:
 Page request - When ASP.NET gets a page request, it decides whether to
parse and compile the page, or there would be a cached version of the page;
accordingly the response is sent.
 Starting of page life cycle - At this stage, the Request and Response objects
are set. If the request is an old request or post back, the IsPostBack property of
the page is set to true. The UICulture property of the page is also set.
 Page initialization - At this stage, the controls on the page are assigned unique
ID by setting the UniqueID property and the themes are applied. For a new
request, postback data is loaded and the control properties are restored to the
view-state values.
 Page load - At this stage, control properties are set using the view state and
control state values.
 Validation - Validate method of the validation control is called and on its
successful execution, the IsValid property of the page is set to true.
 Postback event handling - If the request is a postback (old request), the
related event handler is invoked.
 Page rendering - At this stage, view state for the page and all controls are
saved. The page calls the Render method for each control and the output of
rendering is written to the OutputStream class of the Response property of
page.
 Unload - The rendered page is sent to the client and page properties, such as
Response and Request, are unloaded and all cleanup done.

3. 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] %>

 The Application Directive

The Application directive defines application-specific attributes. It is provided at the top


of the global.aspx file.
The basic syntax of Application directive is:
<%@ Application Language="C#" %>
The attributes of the Application directive are:

Attributes Description

Inherits The name of the class from which to inherit.

Description The text description of the application. Parsers and compilers


ignore this.
Language The language 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, in the page file, a user
control file for linking to a page or user control.
The basic syntax of Assembly directive is:
<%@ Assembly Name ="myassembly" %>
The attributes of the Assembly directive are:

Attributes Description

Name The name of the assembly to be linked.

Src The 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 of Control directive is:
<%@ Control Language="C#" EnableViewState="false" %>
The attributes of the Control directive are:

Attributes Description

AutoEventWireup The Boolean value that enables or disables automatic


association of events to handlers.

ClassName The file name for the control.

Debug The Boolean value that enables or disables compiling with


debug symbols.

Description The text description of the control page, ignored by compiler.

EnableViewState The Boolean value that indicates whether view state is


maintained across page requests.
Explicit For VB language, tells the compiler to use option explicit
mode.

Inherits The class from which the control page inherits.

Language The language for code and script.

Src The filename for the code-behind class.

Strict For 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 implements directive is:
<%@ Implements Interface="interface_name" %>

The Import Directive

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

The Master Directive

The Master directive specifies a page file as being the mater page.
The basic syntax of 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 of 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.
The basic syntax of 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 of Page directive is:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" Trace="true" %>
The attributes of the Page directive are:

Attributes Description

AutoEventWireup The Boolean value that enables or disables page events that are
being automatically bound to methods; for example,
Page_Load.

Buffer The Boolean value that enables or disables HTTP response


buffering.

ClassName The class name for the page.

ClientTarget The browser for which the server controls should render
content.

CodeFile The name of the code behind file.

Debug The Boolean value that enables or disables compilation with


debug symbols.

Description The text description of the page, ignored by the parser.

EnableSessionState It enables, disables, or makes session state read-only.

EnableViewState The Boolean value that enables or disables view state across
page requests.
ErrorPage URL for redirection if an unhandled page exception occurs.

Inherits The name of the code behind or other class.

Language The programming language for code.

Src The file name of the code behind class.

Trace It enables or disables tracing.

TraceMode It indicates how trace messages are displayed, and sorted by


time or category.

Transaction It indicates if transactions are supported.

ValidateRequest The 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 of 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 of Register directive is:
<%@ Register Src="~/footer.ascx" TagName="footer" TagPrefix="Tfooter" %>

4. The ASP.NET Provider Model


There's a well-known design pattern behind the ASP.NET provider model
the strategy pattern. Defined, the strategy pattern indicates an expected behavior (say,
sorting) that can be implemented through a variety of interchangeable algorithms (say,
Quicksort, Mergesort). Each application then selects the algorithm that best fits while keeping
the public, observable behavior and programming API intact.

The provider model is not an application feature that end users can see with their own eyes.
In itself, it doesn't make an application show a richer content, run faster, or be more
responsive. The provider model is an infrastructural feature that improves an application's
architecture by enabling developers and architects to operate under the hood of some system
components. At the same time, it enables developers to build new components that expose
hooks for clients to plug in and customize behavior and settings. Implementing the strategy
pattern doesn't transform an application into an open-source project, allowing anybody to
modify anything. It simply means that you have a simple, elegant, and effective pattern to
make certain parts of your application customizable by clients. At the same time, the
ASP.NET implementation of the pattern the provider model makes you capable of
customizing certain parts of the ASP.NET runtime environment through special classes
named providers from which you can derive your own.

Exemplifying the Provider Model


To see an example of the provider model and its major benefits, let's look at Figure 1-6. The
figure outlines the classic schema for authenticating a user. The blocks of the diagram follow
closely the flow of operations in ASP.NET 1.1.

Can you see the big picture? There are modules in ASP.NET that force you to take (or leave)
a fixed schema of data, a fixed storage medium, and a fixed internal behavior. The most that
you can do is (sometimes) avoid using those modules and write your own from scratch, as we
outlined in the membership example. However, rolling your own replacement is not
necessarily a smart move. You end up with a proprietary and application-specific system that
is not automatically portable from one application to another. In addition, if you hire new
people, you have to train those people before they get accustomed to using your API. Finally,
you have to put forth a lot of effort to make such a proprietary API general enough to be
reusable and extensible in a variety of contexts. (Otherwise, you get to reinvent the wheel
time after time.)

In which way is the provider model a better solution? In the first place, it supplies a well-
documented and common programming interface to perform common tasks. In addition, you
gain the ability to completely control the internal business and data access logic of each API
that falls under its umbrella.

In the end, in ASP.NET 1.1 you often have no other choice than writing your own API to roll
certain functions the way you want. In ASP.NET 2.0, the provider model offers a much better
alternative. So much better that it's practically a crime not to use it.

Figure 1-7 revisits Figure 1-6 in light of the provider model. ASP.NET 2.0 makes available a
bunch of static methods on a global class Membership. (We'll cover the membership API in
great detail in Chapter 15.) At the application level, you always invoke the same method to
perform the same operation (for example, validating user credentials, creating new users,
changing passwords.) Below this common API, though, you can plug in your own provider to
do the job just the way you want. Writing a new provider is as easy as deriving a new class
from a known base and overriding a few well-known methods. The selection of the current
provider for a given task takes place in the configuration file.

Figure 1-7: Membership revisited to use the provider model in ASP.NET 2.0.

5. Asp .NET Server Controls


ASP.NET server controls are the primary controls used in ASP.NET. These controls can be
grouped into the following categories:
 Validation controls - These are used to validate user input and they 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 displaying.
 Personalization controls - These are used for personalization of a page
according to the user preferences, based on user information.
 Login and security controls - These controls provide user authentication.
 Master pages - These controls provide consistent layout and interface
throughout the application.
 Navigation controls - These controls help in navigation. For example, menus,
tree view etc.
 Rich controls - These controls implement special features. For example,
AdRotator, FileUpload, and Calendar control.
The syntax for using server controls is:
<asp:controlType ID ="ControlID" runat="server" Property1=value1 [Property2=value2]

6. Globle.asax Application File


Effectively, global.asax allows you to write code that runs in response to "system level"
events, such as the application starting, a session ending, an application error occurring,
without having to try and shoe-horn that code into each and every page of your site.

You can use it by by choosing Add > New Item > Global Application Class in Visual Studio.
Once you've added the file, you can add code under any of the events that are listed (and
created by default, at least in Visual Studio 2008):

 Application_Start
 Application_End
 Session_Start
 Session_End
 Application_BeginRequest
 Application_AuthenticateRequest
 Application_Error
There are other events that you can also hook into, such as "LogRequest".

Global asax events explained

Application_Init: Fired when an application initializes or is first called. It's invoked for all
HttpApplication object instances.

Application_Disposed: Fired just before an application is destroyed. This is the ideal


location for cleaning up previously used resources.

Application_Error: Fired when an unhandled exception is encountered within the


application.

Application_Start: Fired when the first instance of the HttpApplication class is created. It
allows you to create objects that are accessible by all HttpApplication instances.

Application_End: Fired when the last instance of an HttpApplication class is destroyed. It's
fired only once during an application's lifetime.

Application_BeginRequest: Fired when an application request is received. It's the first event
fired for a request, which is often a page request (URL) that a user enters.

Application_EndRequest: The last event fired for an application request.

Application_PreRequestHandlerExecute: Fired before the ASP.NET page framework


begins executing an event handler like a page or Web service.
Application_PostRequestHandlerExecute: Fired when the ASP.NET page framework is
finished executing an event handler.

Applcation_PreSendRequestHeaders: Fired before the ASP.NET page framework sends


HTTP headers to a requesting client (browser).

Application_PreSendContent: Fired before the ASP.NET page framework sends content to


a requesting client (browser).

Application_AcquireRequestState: Fired when the ASP.NET page framework gets the


current state (Session state) related to the current request.

Application_ReleaseRequestState: Fired when the ASP.NET page framework completes


execution of all event handlers. This results in all state modules to save their current state
data.

Application_ResolveRequestCache: Fired when the ASP.NET page framework completes


an authorization request. It allows caching modules to serve the request from the cache, thus
bypassing handler execution.

Application_UpdateRequestCache: Fired when the ASP.NET page framework completes


handler execution to allow caching modules to store responses to be used to handle
subsequent requests.

Application_AuthenticateRequest: Fired when the security module has established the


current user's identity as valid. At this point, the user's credentials have been validated.

Application_AuthorizeRequest: Fired when the security module has verified that a user can
access resources.

Session_Start: Fired when a new user visits the application Web site.

Session_End: Fired when a user's session times out, ends, or they leave the application Web
site.

7. States

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 posted 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.

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 such as inventory, supplier list,
customer record, or shopping cart. It can also keep information about the user and his
preferences, and keep the track of pending operations.
void StoreSessionInfo()
{
String fromuser = TextBox1.Text;
Session["fromuser"] = fromuser;
}

void RetrieveSessionInfo()
{
String fromuser = Session["fromuser"];
Label1.Text = fromuser;
}

Application State

The 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 data is generally maintained by writing handlers for the events:

 Application_Start
 Application_End
 Application_Error
 Session_Start
 Session_End

8. Web Form Slandered Control


Label control
Label control and the Literal control are used to display text in a page. Literal control only
supports text property, but the Label control has a number of formatting properties.
By default, a Label control renders its content in an HTML <span> tag. After executing your
application, you can see the respective label <span> tag by using view source on the browser.

The Label control displays text at a particular position on a Web page. Generally Label
control is used as the caption of a TextBox.

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

Literal control
It is light weight control. The Literal Control is similar to the Label Control but it does not
support properties like BackColor, ForeColor, BorderColor, BorderStyle, BorderWidth, etc.
Also you cannot apply a style to a literal control. It is used to display static text on a Web
page without adding additional properties or HTML tags.

<asp:Literal ID="Literal1" runat="server">It is a Literal Control</asp:Literal>

TextBox control
The TextBox control is frequently used and one of the most important control. It is used to
collect information from a user. It is an input control which is used to input the data.

The TextBox control contains an important property called TextMode. By using this property
you can set textbox as

 SingleLine
 MultiLine
 Password
SingleLine mode is default mode of textbox control and allows the user to enter data in a
single line of text.

Password mode masks (text is hidden) the values entered by the user.
MultiLine mode enables user to enter text in more than one line. You can use MultiLine
mode, in combination with the Columns and Rows properties. Column specifies the number
of columns (Width) and rows specify the number of rows (Height) to display.

Another important property of textbox control is MaxLength. It sets the limit on the number
of character that a user can enter into textbox.

TextBox control supports the following event:

TextChanged: It fires, when you change the content or text of the textbox control.
TextChanged event only fire, when AutoPostBack property has the value True. By default
AutoPostBack property has the value false.

If you change the text of the TextBox control and press tab key from the keyboard, the form
is automatically posted back to the server.

Button Controls
There are three types of button control available in ASP.NET:

 Button
 Link Button
 Image Button
Button control

Button control postbacks the web page to webserver, when user clicks the button. A Button
control can be used as a submit button (default) or a command button.

You can also use Button control as a command button. It is useful when you want to group a
set of buttons. Button control has property called CommandName. Assign unique
CommandName value for each button. Create a single command event handler explicitly, that
will handle the event of all command buttons.
Suppose that you have four buttons as given below and want to create all buttons as a
command button.

Provide a unique CommandName to each button. As example First, Last, Previous, Next.

Example: Default.aspx

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


Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:Button ID="Button1" runat="server" OnCommand="Navigate_Command"
Text="<<" CommandName="First" Width="65px"/>
<asp:Button ID="Button2" runat="server" OnCommand="Navigate_Command"
Text="<" CommandName="Previous" Width="65px"/>
<asp:Button ID="Button3" runat="server" OnCommand="Navigate_Command"
Text=">" CommandName="Next" Width="65px"/>
<asp:Button ID="Button4" runat="server" OnCommand="Navigate_Command"
Text=">>" CommandName="Last" Width="65px"/>
</form>
</body>
</html>

Default.aspx.cs

using System;
using System.Web.UI.WebControls;
using System.Drawing;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Navigate_Command(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "First":
Response.Write("First");
break;
case "Previous":
Response.Write("Previous");
break;
case "Next":
Response.Write("Next");
break;
case "Last":
Response.Write("Last");
break;
}
}
}

CausesValidation property: It checks the page validation. By default this property is true
for button control. If you set CauseValidation value to false, then it will bypass the page
validation.

LinkButton

LinkButton control displays a link instead of a push button. By default, a LinkButton control
is a Submit button.

Some of the important properties of LinkButton Control are:


CausesValidation: If this property is set as true then validation will be performed when
Linkbutton is be clicked. Otherwise it will bypass the validation.

PostBackUrl: It posts a form to a particular page when the LinkButton control is clicked.

ValidationGroup: The group of controls when the LinkButton control causes posts back to
the server.

OnClick: Attach a server side method that will fire when this button will be clicked.

OnClientClick: You can attach a client-side script that executes when the LinkButton is
clicked.

ImageButton

The ImageButton control is similar to Button and LinkButton controls but it always displays
an image. It works as a clickable image. Most of the properties are same as Button or
LinkButton.
The main difference is ImageUrl and AlternateText property. ImageUrl Gets or Sets the
location of the image. AlternateText property provides alternate text for the image.

Let us take an example that will show the use of TextBox and Different type of Button.
Example: Default.aspx

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


Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1
{
width: 103px;
}
.auto-style3
{
width: 165px;
}
.auto-style4
{
width: 143px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<table style="width: 76%;">
<tr>
<td class="auto-style1">
<asp:Label ID="Label1" runat="server" Text="Label">EmployeeName</asp:Label>
</td>
<td class="auto-style4">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
<td class="auto-style3"> </td>
</tr>
<tr>
<td class="auto-style1">
<asp:Label ID="Label2" runat="server" Text="Label">Password</asp:Label>
</td>
<td class="auto-style4">
<asp:TextBox ID="TextBox2" runat="server" TextMode="Password"> </asp:TextBox>
</td>
<td class="auto-style3"> </td>
</tr>
<tr>
<td class="auto-style1">
<asp:Label ID="Label3" runat="server" Text="Label">Address</asp:Label>
</td>
<td class="auto-style4">
<asp:TextBox ID="TextBox3" runat="server" Height="54px" TextMode="MultiLine"
Width="211px"></asp:TextBox>
</td>
<td class="auto-style3"> </td>
</tr>
<tr>
<td class="auto-style1">
<asp:Button ID="Button1" runat="server" Text="Button" />
</td>
<td class="auto-style4">
<asp:LinkButton ID="LinkButton1" runat="server">Submit</asp:LinkButton>
</td>
<td class="auto-style3">
<asp:ImageButton ID="ImageButton1" runat="server" AlternateText="This is Image
Button" ImageUrl="~/logo.gif" BorderColor="Blue" BorderStyle="Solid"
BorderWidth="2px" PostBackUrl="~/Default2.aspx" />
</td>
</tr>
</table>
</form>
</body>
</html>
CheckBox Control
A CheckBox control is used to select a single or multiple options from the available choices.
For example a person can select more than one cities for travelling.

Important Properties of the CheckBox Control

Checked: It is used to check if the check box is checked or not. This is a boolean property.

Text: It is used to get or set the text associated with the check box control. This is a string
property.

TextAlign: It enables you to set the text right or left of the check box. By default TextAlign
property is set to right.

AutoPostBack: If you want that when you change the status of checkbox (check or
uncheck), then set AutoPostBack property true. By default this property is set to false.

Methods:
Focus(): It sets the input focus, to a specific checkbox. Call this method for that check box
control.

Events:
CheckedChanged: This event is fired when the checked status of the checkbox control is
changed. AutoPostBack property should be set as true to fire this event.
RadioButton Control
Radio Button control is used, when you want to select only one option from the available
choices. RadioButton control works in a group. There may be more than one group of radio
button. You can select only one RadioButton control from particular radio button group.

9. TreeView

The TreeView control is an object model in ASP.Net which allows creation of nodes
dynamically. It will have the Root, Parent and Leaf.

The TreeView control has properties and events. It has some characteristics.

 TreeView node can navigate to some other pages


 The images and properties can be set to the nodes
 It can have the lines, checkbox and images
 It can set dynamically expand/collapse
 The nodes can be created on demand

The sample treeview code.

<asp:TreeView ID="TreeView1" runat="server">


<Nodes>
<asp:TreeNode Value="Child1" PopulateOnDemand="true" ShowCheckBox="true"
Expanded="True" Text="1">
<asp:TreeNode Value="Grandchild1" Text="A" />
<asp:TreeNode Value="Grandchild2" Text="B" />
</asp:TreeNode>
<asp:TreeNode Value="Child2" Text="2" />
<asp:TreeNode Value="Child3" Expanded="True" Text="3">
<asp:TreeNode Value="Grandchild1" Text="A" />
</asp:TreeNode>
</Nodes>
</asp:TreeView>

There are some properties that are useful for defining the behavior of the TreeView. These
properties are Boolean value based.

1. PopulateOnDemand - It will populate the node under another node on the


demand. It will help to increase the performance; it would not create and render
at the time of initial loading.
2. ShowCheckBox - This property used to set the check-box is required or not.
3. Expand - It accepts Boolean property to set the node has to be expanded or
collapsed at the time of rendering.
4. ShowLines - This is used to show the flow of the nodes in the lines.

10. Menu control


The ASP.NET Menu control allows you to develop both statically and dynamically displayed
menus for your ASP.NET Web pages.

Static Display Behavior

You can control static display behavior by using the StaticDisplayLevels property of the
Menu control. The StaticDisplayLevels property indicates how many levels to display
statically from the root of the menu. For example, if StaticDisplayLevels is set to 3, your
menu will be expanded to statically display its first three levels. The minimum static display
level is 1, and the control will throw an exception if the value is set to 0 or a negative number.

Dynamic Display Behavior

The MaximumDinamicDisplayLevel property specifies how many levels of dynamically


appearing menu nodes should be displayed after the static display level. For example, if your
menu has a static level of 3 and a dynamic level of 2, the first three levels of your menu
would be statically displayed, while the next two levels would be dynamic.

Defining Menu Content

You can define content for the Menu control in two ways: by adding individual MenuItem
objects (declaratively or programmatically), and by data binding the control to an XML data
source.
Adding Menu Items Manually

You can add individual menu items to the control by specifying them in the Items property.
The Items property is a collection of MenuItem objects. The following example shows the
declarative markup for a Menu control with three items, each of which has two child items:

<asp:Menu ID="Menu1" runat="server" StaticDisplayLevels="3">


<Items>
<asp:MenuItem Text="File" Value="File">
<asp:MenuItem Text="New" Value="New"></asp:MenuItem>
<asp:MenuItem Text="Open" Value="Open"></asp:MenuItem>
</asp:MenuItem>
<asp:MenuItem Text="Edit" Value="Edit">
<asp:MenuItem Text="Copy" Value="Copy"></asp:MenuItem>
<asp:MenuItem Text="Paste" Value="Paste"></asp:MenuItem>
</asp:MenuItem>
<asp:MenuItem Text="View" Value="View">
<asp:MenuItem Text="Normal" Value="Normal"></asp:MenuItem>
<asp:MenuItem Text="Preview" Value="Preview"></asp:MenuItem>
</asp:MenuItem>
</Items>

</asp:Menu>

11. Site Map


Creating high quality content for web site requires hard work. Because of that, webmasters
usually want to be sure that all produced content is visible to web spiders so it can be indexed
and possibly attract visits from popular search engines, like Google, Live or Yahoo.
Webmasters often solved this problem by adding one more page, named site map page. That
was common HTML page which contains hyperlinks to all other pages on web site, so visitor
or web spider could find all content if classic navigation through menus didn't work properly.

Google recognized this problem and introduced site maps formatted as XML files. Site maps
are accepted later by Microsoft and Yahoo. ASP.NET 2.0 goes one step beyond and provides
new .sitemap XML files that work with Menu, TreeView and SiteMapPath controls to enable
easier navigation. Although Google site map and ASP.NET .sitemap are both XML files,
they don't use same schema.

Web.sitemap file in ASP.NET


Web.sitemap file must be placed in a root of web application. It is an XML file that describes
hierarchical web site structure. You can make new Web.sitemap file in Visual Studio if you
go on menu File --> New File... and select Site Map from Visual Studio Templates in "Add
New Item" dialog. Click OK and you'll get new xml file with this content:
<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
<siteMapNode url="" title="" description="">
<siteMapNode url="" title="" description="" />
<siteMapNode url="" title="" description="" />
</siteMapNode>
</siteMap>
As you can see, it is an XML file. There is interesting element siteMapNode which we can
use to describe the structure of our web site. Here is an example of typical Web.sitemap file
for small web site.
<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
<siteMapNode url="~/Default.aspx" title="Home" description="Home page of our web
site">
<siteMapNode url="~/News.aspx" title="News" description="Company news." />
<siteMapNode url="~/Products/Default.aspx" title="Products" description="Our
products" >
<siteMapNode url="~/Products/Product1.aspx" title="First product" description="This
is first product." />
<siteMapNode url="~/Products/Product2.aspx" title="Second
product" description="This is second product." />
</siteMapNode>
<siteMapNode url="~/Contact.aspx" title="Contact Us" description="Here you can
contact us." />
<siteMapNode url="~/Order.aspx" title="Order" description="Purchase our products
online." />
</siteMapNode>
</siteMap>
Let's analyze this file. You can see it is pretty self explanatory. We practically use only one
tag, named siteMapNode to describe url, title and short description of every page on web
site. Url values start with "~/" which indicates root of the web application. You also can add
urls that are outside of your web application. There could be only
one siteMapNode inside siteMap tag. But, inside first siteMapNode could be many
nested siteMapNode tags to describe hierarchical structure between pages.

12. WEB PARTS

Web Parts now a day's most of the websites is using this technology extensively.

If you just clearly observe any of the websites, you can observe the difference web parts
concept is making on the web pages.
The Level of interactive Ness we can find is that we feel like we are designing that web page.
So what if we can design and code our own WebPages that will accumulate the concept of
web parts. we can code and explore that as easily as we have done with the other controls in
the previous sessions.

We can compose web parts pages from "web parts", which can be web controls, user
controls.

Component of Web Parts:

The web parts consist of different components like:


 Web Part Manager
 Web Part Zone
 Catalog Part
 Catalog Zone
 Connections Zone
 Editor Part
 Editor Zone

In this exercise, lets see the usage of Web Part Manager, WebPartZone and how to use
conventional Web Controls (ASP.NET CONTROLS/User Controls) as Web Parts.

Web parts manager consists of each division of the web parts in the order of the module
consistency.

A single Web Parts page can ONLY have one instance of a "WebPartManager Control".

The usage of WebPartManager control is that it manages all the other Web Parts controls on
that page, including Web Part Zones (Web Zone class).

The WebPartManager control, in turn, maintains a collection of all the Web Part controls on a
page in its Web Parts collection. This doesn't have any User Interface and is not visible at run
time (similar to the Timer Control)

Web Part Zone uses


 Web Part Zone can contain one or more Web Part controls.
 This provides the layout for the Controls it contains. A single ASPX page can
contain one or more Web Part Zones.
 A Web Part Control can be any of the controls in the toolbox or even the
customized user controls.
How to create a Web Part Page:

Step 1: Create a table, which can accommodate 3 rows and 1 column.


Step 2: Add a "Web Part Manager" to the page by dragging from the Tool Box under the
Web Parts Category
Step 3: Add a "Web Part Zone" Control to the page by dragging from the Tool Box
Step 4: Add one more "Web Part Zone" Control to the page by dragging from the Tool Box.
You can add as many zones basing on your requirement. Now each zone is a Separate Web
Part Area and you can add control (Server Controls) on to the Web Part Zone control.

Step 5: After adding the Web Part Zone Controls, the page should look like this:

Figure 1

Creating web usercontrol and adding it in web zone control

Step 6: Right Click in the solution Explorer and select "Add New Item" from the menu.
Step 7: Select "Web User Control" as the type and name it as "myusercontrol.ascx".
Step 8: Add a table having 1 row and 1 column and add the following text inside the <td>
</td>
Step 9: "Welcome to webparts home". The web parts HomePage is highly personalizable. To
personalize this page, use the links in the upper corner.
Step 10: HTML Content can be added basing on your interest.
Step 11: Switch to Design View and drag and drop myusercontrol.ascx in webpartzone1.
Step 12: Now your Page in Design View will look similar to the one below:
Figure 2

Step 13: Change the title of the user control to "Webparts". This can be done by selecting the
user control and switching to "Source".
Step 14: Inside the <Zone Template> you can find this tag:
1. <uc1:myusercontrol ID="Myusercontrol1" runat="server" />

Change this to:

1. <uc1:myusercontrol ID="Myusercontrol1" runat="server" Title=”WebParts”/>


Step 15: Any web control can be added to the Web Part Zone. To prove this pick any control
from the tool box and drop it in the "Web Part Zone2". For interactive ness, I am using
Calendar Control in my Web Part Zone2.
Step 16: Change the Title of the Calendar Control to "MyCalendar Control" in the same way
as you have done for myusercontrol.ascx.
Step 17: After adding Calendar Control, my page looks like this in the Run Mode:
Step 18: Now comes the most interesting part of Web Parts.

The Beauty of "Web Parts" is that it maintains its own Database for storing the User
Preferences by assigning a unique User ID to each and every user accessing the "Web Parts".

To prove this lets see the example I have specified below:


Figure 3

Step 19: On the Browser you can see a smart tag (the drop down arrow in blue on the top
right hand corner for each zone). If you click on any of the tags, your pages will look similar
to this:

Figure 4

Step 20: You will be provided with two options.


1. Minimize
2. Close
Step 21: Click on "Minimize" your page will look similar to this:

Figure 5

Step 22: Close your Browser and come back to the Design Part of the Page.
Step 23: Now execute your application again to check the preferences are saved or not.
Step 24: Interestingly, if you can observe the settings you have made to Zone1 are applied
and you can see that WebPartZone1 is still minimized.
Step 25: So your application on the Browser should be similar to this:
Figure 6

Editor Zone Control

A key feature of Web Parts is the ability of end users to personalize Web pages and save their
personalized settings. One aspect of modifying Web Parts pages includes editing the
appearance, layout, behavior, and other properties of the visible WebPart controls.

Components of Editor Zone Control

AppearanceEditorPart : The AppearanceEditorPart control enables end users to edit several


UI properties of a WebPart control.

BehaviorEditorPart The BehaviorEditorPart Web server control is an editor part control


that enables end users to change several user interface (UI) properties on an
associated WebPart control at run time.

LayoutEditorPart : user-customizable features and corresponding WebPart control


property values that are editable by using the AppearanceEditorPart control.
PropertyGridEditorPart :The PropertyGridEditorPart provides a generic user interface (UI)
that lets users edit custom properties on WebPart controls and on server controls
in WebPartZoneBase zones.

Connection Zone Control


Provides a user interface (UI) that enables users to form connections between WebPart and
other server controls that reside in WebPartZoneBase zones.

 Enables you to switch display modes on the Web page.

 Contains the code for a ZIP Code interface, and two WebPart controls acting as
the provider and the consumer for a connection.

 Hosts all the controls, demonstrates how to declare


an <asp:connectionszone> element, and sets a number of properties on the
connections zone declaratively and programmatically.

 An explanation of how the example works in a browser.


13. Validation Controls in ASP.NET

An important aspect of creating ASP.NET Web pages for user input is to be able to check
that the information users enter is valid. ASP.NET provides a set of validation controls that
provide an easy-to-use but powerful way to check for errors and, if necessary, display
messages to the user.

There are six types of validation controls in ASP.NET


1. RequiredFieldValidation Control
2. CompareValidator Control
3. RangeValidator Control
4.
5. RegularExpressionValidator Control
6. CustomValidator Control
7. ValidationSummary

RequiredFieldValidation Control

The RequiredFieldValidator control is simple validation control, which checks to see if the
data is entered for the input control. You can have a RequiredFieldValidator control for each
form element on which you wish to enforce Mandatory Field rule.
1. <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
2. Style="top: 98px; left: 367px; position: absolute; height: 26px; width: 162px"
3. ErrorMessage="password required" ControlToValidate="TextBox2">
4. </asp:RequiredFieldValidator>

CompareValidator Control

The CompareValidator control allows you to make comparison to compare data entered in an
input control with a constant value or a value in a different control.

It can most commonly be used when you need to confirm password entered by the user at the
registration time. The data is always case sensitive.
1. <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" Styl
e="top: 145px;
2. left: 367px; position: absolute; height: 26px; width: 162px" ErrorMessage=
"password required"
3. ControlToValidate="TextBox3"></asp:RequiredFieldValidator>

RangeValidator Control
The RangeValidator Server Control is another validator control, which checks to see if a
control value is within a valid range. The attributes that are necessary to this control are:
MaximumValue, MinimumValue, and Type.
1. <asp:RangeValidator ID="RangeValidator1" runat="server"
2. Style="top: 194px; left: 365px; position: absolute; height: 22px; width: 105px"
3. ErrorMessage="RangeValidator" ControlToValidate="TextBox4" MaximumVal
ue="100" MinimumValue="18" Type="Integer"></asp:RangeValidator>

RegularExpressionValidator Control

It is used to validate complex expressions. These expressions can be phone number, email
address, zip code and many more. Using Regular Expression Validator is very simple. Simply
set the ValidationExpression property to any type of expression you want and it will validate
it.

In the example I have checked the email id format:


1. <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="se
rver" Style="top: 234px;
2. left: 366px; position: absolute; height: 22px; width: 177px"
3. ErrorMessage="RegularExpressionValidator" ControlToValidate="TextBo
x5"
4. ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\
w+)*"></asp:RegularExpressionValidator>

ValidationSummary

ASP.NET has provided an additional control that complements the validator controls.

The ValidationSummary control is reporting control, which is used by the other validation
controls on a page.

You can use this validation control to consolidate errors reporting for all the validation errors
that occur on a page instead of leaving this up to each and every individual validation control.

The validation summary control will collect all the error messages of all the non-valid
controls and put them in a tidy list.
1. <asp:ValidationSummary ID="ValidationSummary1" runat="server"
2. style="top: 390px; left: 44px; position: absolute; height: 38px; width: 625p
x" />

CustomValidator Control

You can solve your purpose with ASP.NET validation control. But if you still don't find
solution you can create your own custom validator control.
The CustomValidator Control can be used on client side and server side. JavaScript is used to
do client validation and you can use any .NET language to do server side validation.

I will explain you CustomValidator using server side. You should rely more on server side
validation.

To write CustomValidator on server side you override ServerValidate event.

14. GridView:
Introduction

The GridView control displays the values of a data source in a table. Each column represents
a field, while each row represents a record. The GridView control supports the following
features:
 Binding to data source controls, such as SqlDataSource.
 Built-in sort capabilities.
 Built-in update and delete capabilities.
 Built-in paging capabilities.
 Built-in row selection capabilities.
 Programmatic access to the GridView object model to dynamically set
properties, handle events, and so on.
 Multiple key fields.
 Multiple data fields for the hyperlink columns.
 Customizable appearance through themes and styles.
Creating a GridView
1. <asp:GridView ID="gridService" runat="server" AutoGenerateColumns="false
" ShowFooter="true" >
2. <Columns>
3. <asp:TemplateField ItemStyle-Width="30px" HeaderText="SR.
NO">
4. <ItemTemplate>
5. <asp:Label ID="lblID" runat="server"
6. Text='<%#Eval("service_id")%>'></asp:Label>
7. </ItemTemplate>
8. </asp:TemplateField>
9. <asp:TemplateField ItemStyle-Width="600px" HeaderText="Ser
vice">
10. <ItemTemplate>
11. <asp:Label ID="lblService" runat="server" Text='<
%#Eval("service_name")%>'></asp:Label>
12. </ItemTemplate>
13. <EditItemTemplate>
14. <asp:TextBox ID="txtService" runat="server" Text='<
%#Eval("service_name")%>'></asp:TextBox>
15. </EditItemTemplate>
16. <FooterTemplate>
17. <asp:TextBox ID="txtService" runat="server"></
asp:TextBox>
18. </FooterTemplate>
19. </asp:TemplateField>
20. <asp:TemplateField ItemStyle-Width="100px" HeaderText="Ser
vice Photo">
21. <ItemTemplate>
22. <img src='<%# Eval("service_image")%>' alt='<%#
23. Eval("service_image")%>' height="50px"
24. width="50px" />
25. </ItemTemplate>
26. <EditItemTemplate>
27. <asp:FileUpload ID="fuService" runat="server" />
28. </EditItemTemplate>
29. <FooterTemplate>
30. <asp:FileUpload ID="fuService" runat="server" />
31. </FooterTemplate>
32. </asp:TemplateField>
33. <asp:TemplateField>
34. <ItemTemplate>
35. <asp:LinkButton ID="lnkRemove" runat="server" Comman
dArgument='<%#
36. Eval("service_id")%>'
37. OnClientClick="return confirm('Do you want to delete?')"

38. Text="Delete"></asp:LinkButton>
39. </ItemTemplate>
40. <FooterTemplate>
41. <asp:Button ID="btnAdd" runat="server" Text="Add" OnCl
ick="AddService"/>
42. </FooterTemplate>
43. </asp:TemplateField>
44. <asp:CommandField ShowEditButton="True" />
45. </Columns>
46. </asp:GridView>

Binding GridView
1. gridService.DataSource = Table_Student;
2. gridService.DataBind();
15.Data List Control

Introduction

DataList is a Databound control to display and manipulate data in a web application. It is a


composite control that can combine other ASP.Net controls and it is present in the form. The
DataList appearance is controlled by its template fields.

The following template fields are supported by the DataList control:


 Itemtemplate: It specifies the Items present in the Datasource, it renders itself
in the browser as many rows present in the data source collection.
 EditItemTemplate: Used to provide edit permissions to the user.
 HeaderTemplate: Used to display header text to the data source collection.
 FooterTemplate: Used to display footer text to the data source collection.
 ItemStyle: Used to apply styles to an ItemTemplate.
 EditStyle: Used to apply styles to an EditItemTemplate
 HeaderStyle: Used to apply styles to a HeaderTemplate
 FooterStyle: Used to apply styles to a FooterTemplate.

Creating DataList
1. <asp:DataList ID="dl1" runat="server"
2. RepeatDirection="Horizontal"
3. RepeatColumns="3">
4. <HeaderTemplate>
5. <table>
6. <tr>
7. <td>
8. <h1>Student Information</h1>
9. </td>
10. </tr>
11. </table>
12. </HeaderTemplate>
13. <ItemStyle CssClass="itemstyle" />
14. <ItemTemplate>
15. <table border="1">
16. <tr>
17. <td>Employee ID:</td>
18. <td>
19. <asp:Label ID="lblempid" runat="server" Text='<%# Eva
l("EmpId") %>'>
20. </asp:Label>
21. </td>
22. <td rowspan="5">
23. <asp:Image ID="empimg" runat="server" ImageUrl='
24. <%# "~/Images/" + Eval("EmpImage") %>' Height="1
80px" Width="200px" />
25. </td>
26. </tr>
27. <tr>
28. <td>Employee Name:</td>
29. <td>
30. <asp:Label ID="lblempname" runat="server" Text='<
%# Eval("EmpName") %>'>
31. </asp:Label>
32. </td>
33. </tr>
34.
35.
36. </table>
37. </ItemTemplate>
38.
39. </asp:DataList>

Binding DataList
1. protected void Page_Load(object sender, EventArgs e)
2. {
3. if (!IsPostBack)
4. {
5. Bind();
6. }
7. }
8. public void Bind()
9. {
10. SqlCommand cmd = new SqlCommand("select * from Employee", con);
11. SqlDataAdapter da = new SqlDataAdapter(cmd);
12. DataSet ds = new DataSet(); //dataset is set of tables
13. da.Fill(ds, "Employee");
14.
15. // binding datalist with 0th table of dataset
16.
17. dl1.DataSource = ds.Tables[0];
18. dl1.DataBind();
19. }

16.Detail view control


DetailsView control used to display a single database record of table layout in ASP.Net.
Means it works with a single data item at a time. DetailsView control used to display record,
insert, update, and delete records from database.
Creating Detail View
<asp:DetailsView ID="DetailsView1" runat="server"
BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px"
CellPadding="2" DataKeyNames="ID" ForeColor="Black" GridLines="None"
Height="50px" >
<FooterStyle BackColor="Tan" />
<PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue"
HorizontalAlign="Center" />
<HeaderStyle BackColor="Tan" Font-Bold="True" />
<EditRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
<AlternatingRowStyle BackColor="PaleGoldenrod" />
</asp:DetailsView>

Binding Detal View


protected void btnSave_Click(object sender, EventArgs e)
{

SqlConnection SQLConn = new SqlConnection("Data Source=COMPUTER_1\\


SQLEXPRESS;Initial Catalog=BOOK;Integrated Security=True");
SqlDataAdapter SQLAdapter = new SqlDataAdapter("insert into UserMst values ('"+
txtname.Text +"','"+ txtcity.Text +"')", SQLConn);
DataTable DT = new DataTable();
SQLAdapter.Fill(DT);
BindDetailsView();

}
private void BindDetailsView()
{

SqlConnection SQLConn = new SqlConnection("Data Source=COMPUTER_1\\


SQLEXPRESS;Initial Catalog=BOOK;Integrated Security=True");
SqlDataAdapter SQLAdapter = new SqlDataAdapter("select * from UserMst", SQLConn);
DataTable DT = new DataTable();
SQLAdapter.Fill(DT);
DetailsView1.DataSource = DT;
DetailsView1.DataBind();
}

17.Form View Control

FormView Control is introduced with ASP.NET 2.0. It is often used in master/details scenario
with GridView, DataList or Repeater control. FormView Control is similar to DeatilsView control.
Both controls enable showing of single record from data source. The main difference between
FormView and DeatilsView controls is that FormView control allows using of templates for
displaying a record instead of row fields used in DetailsView. Unlike DetailsView, FormView
control doesn't have predefined data layout. Developer needs to create a template first and
specify controls and formatting to display single record from data source. Because of that
developer have full control over layout and it is pretty easy to add validation capabilities.

Creating form view control;

<asp:FormView
id="frmBooks"
DataSourceID="SqlDataSource1"
Runat="server">
<ItemTemplate>
<b><u><%# Eval("TITLE")%></u></b>
<br />
<b>Serial Number:</b>
<%# Eval("ID")%>
<br />
<b>Author:</b>
<%# Eval("AUTHOR")%>
<br />
<b>Price:</b>
<%# Eval("PRICE")%>
</ItemTemplate>
</asp:FormView>

18.Repeater Control
The Repeater control is used to display a repeated list of items that are
bound to the control. The Repeater control may be bound to a database
table, an XML file, or another list of items.

Repeater is a Data Bind Control. Data Bind Controls are container controls.
Data Binding is the process of creating a link between the data source and
the presentation UI to display the data. ASP .Net provides rich and wide
variety of controls, which can be bound to the data.

Repeater has 5 inline template to format it:


1. <HeaderTemplate>
2. <FooterTemplate>
3. <ItemTemplate>
4. <AlternatingItemTemplate>
5. <SeperatorTemplate>
6. <AlternatingItemTemplate>

Creating repeater control

1. <asp:Repeater ID="RepeatInformation" runat="server">


2. <HeaderTemplate>
3. <table class="tblcolor">
4. <tr>
5. <b>
6. <td>
7. Roll No
8. </td>
9. <td>
10. Student Name
11. </td>
12. <td>
13. Total Fees
14. </td>
15. </b>
16. </tr>
17. </HeaderTemplate>
18. <ItemTemplate>
19. <tr class="tblrowcolor">
20. <td>
21. <
%#DataBinder.Eval(Container,"DataItem.RollNo")%>
22. </td>
23. <td>
24. <
%#DataBinder.Eval(Container,"DataItem.Name")%>
25. </td>
26. <td>
27. <
%#DataBinder.Eval(Container,"DataItem.Fees")%>
28. </td>
29. </tr>
30. </ItemTemplate>
31. <SeparatorTemplate>
32. <tr>
33. <td>
34. <hr />
35. </td>
36. <td>
37. <hr />
38. </td>
39. <td>
40. <hr />
41. </td>
42. </tr>
43. </SeparatorTemplate>
44. <AlternatingItemTemplate>
45. <tr>
46. <td>
47. <
%#DataBinder.Eval(Container,"DataItem.RollNo")%>
48. </td>
49. <td>
50. <
%#DataBinder.Eval(Container,"DataItem.Name")%>
51. </td>
52. <td>
53. <
%#DataBinder.Eval(Container,"DataItem.Fees")%>
54. </td>
55. </tr>
56. </AlternatingItemTemplate>
57. <SeparatorTemplate>
58. <tr>
59. <td>
60. <hr />
61. </td>
62. <td>
63. <hr />
64. </td>
65. <td>
66. <hr />
67. </td>
68. </tr>
69. </SeparatorTemplate>
70. <FooterTemplate>
71. <tr>
72. <td>
73. School Records displayed
74. </td>
75. </tr>
76. </table>
77. </FooterTemplate>
78. </asp:Repeater>

Binding Repeater control


1. protected void Page_Load(object sender, EventArgs e)
2. {
3. con = new SqlConnection(ConfigurationManager.
ConnectionStrings["constr"].ConnectionString);
4. cmd.Connection = con;
5. cmd.CommandText = "select * from student";
6. con.Open();
7. RepeatInformation.DataSource = cmd.ExecuteRea
der();
8. RepeatInformation.DataBind();
9. con.Close();
10. }
19.Difference between repeater and gridview control
The GridView : it supports paging but it doesn't provide a flexible layout ,
since its mainly used to display the data in a table based layout.And If we
looked at data inserting , the Gridview doesn't have a built in support for
inserting data( since it doesn't call the insert method of it underlying data
source when you click on a button with a CommadName set to "Insert" ).
The Repeater control : you will find that it provides a flexible layout but it
doesn't support data grouping ,inserting,deleting , updating and paging
through the data .
The Repeater and GridView controls are used differently. A GridView control
is used when you want to display a set of data in a table format. A Repeater
is when you want to display data repeatedly, but not necessarily in a tabular
format. If you want a table, use a GridView, otherwise use a Repeater. The
speed of loading/updating is negligible between the two. It sounds like the
GridView is what you are probably looking for.

20.Sql Data Source Control


Introduction

SqlDataSource control is a data source control provided in ASP.NET to connect to database


providers such as SQL, OLEDB, ODBC, and Oracle. This control only establishes a
connection with the data source; it does not display data on the web page. The data is
displayed by binding the SqlDataSource control to a data-bound control such as a GridView
or DataList. These data-bound controls, in turn, display the data on the web page. The
SqlDataSource control also supports editing, updating, deleting, and sorting of the records
retrieved from the database. This support to manipulate the data in the data source can be
implemented in data-bound controls without writing any code. In other words, a
SqlDataSource control allows you to access databases without creating a Connection,
Command, or a Data Reader object.

Adding SqlDataSource Control

A SqlDataSource control is added to the webform using markup or by dragging it from the
Toolbox and dropping it on the web form. The code below shows the markup to create a
SqlDataSource control.

<asp:SqlDataSource ID=”sqldsSuppliers” runat=”server”>


</asp:SqlDataSource>

Configuring SqlDataSource Control

<asp:SqlDataSource ID=”sqldsSuppliers” runat=”server” ConnectionString=”Data


Source=10.2.1.51\SQLEXPRESS;Initial Catalog=Northwind; Integrated Security=True”
SelectCommand=”select * from NWSupplierss;”>
</asp:SqlDataSource>
Binding to a Data Bound Control DataList

<asp:DataList ID=”dlstSuppliers” runat=”server” backcolor=”LightGoldenrodYellow”


BorderColor=”Tan” BorderWidth=”1px” CellPadding=”2” DataSourceID=”sqldsSuppliers”
Font-Name=”verdana” Font-Size=”Smaller” ForeColor=”Black”>
</asp:Datalist>

You might also like