Anda di halaman 1dari 188

ASP.

net
1


CONTENTS

1. Introduction To MS.net
1.1 Microsoft Development technology
1.2 Versions Of Ms.net
1.3 Features according to versions of .net
1.4 MS.net Framework
1.4.1 MS.net framework
1.4.2 Microsoft Products
1.4.3 MS.net Services
1.4.4 MS.net Servers
1.4.5 MS.net Tools
1.4.6 MS.net Languages
1.4.7 MS.net Technologies

1.5 MS.net Architecture
1.5.1 Application layer
1.5.2 Base class Layer
1.5.3 Translating layer

1.6 Intermediate Language
1.6.1Metadata
1.6.2 Code
1.6.3 Resource
1.6.4 Manifest

1.7 Common Language runtime
1.7.1 IL Loader
1.7.2 Access Controller
1.7.2.1 CTS
1.7.2.2 CLS
1.7.2.3 CAS
1.7.2.4 RBS
1.7.2.5 Memory Management
1.7.2.6 Just In Time Compiler
1.7.2.6.1 Pre JIT
1.7.2.6.2 Standard JIT
1.7.2.6.3 Echno JIT

ASP.net
2




2. Hyper Text Markup Language
2.1 Features Of HTML
2.2 Tag References
2.2.1 Basic Tag
2.2.2 Link Tag
2.2.3 Text Formatting Tag
2.2.4 List Tags
2.2.5 Multimedia Tag
2.2.6 Font Tag
2.2.7 Frame Tag
I. Form Tag
2.3 Button controls
3 Scripting Languages
3.1 Different Types of Scripting languages
3.2 Features Of scripting Languages
4 JavaScript
4.1 Variables in JavaScript
4.2 Functions in Javascript
4.3 Working with JavaScript
4.4 JavaScript Object hierarchy
4.5 Objects in JavaScript
5 Dynamic Hypertext Markup Language
5.1 Cascading style sheets
5.1.1 Types Of CSS
5.1.1.1 Inline style sheet
5.1.1.2 Embedded style sheet
5.1.1.2.1 tag as selector
5.1.1.2.2 class as selector
5.1.1.2.3 ID as selector
5.1.1.3 External style sheet
5.1.1.4 Imported style sheet
6 ASP.NET
6.1 Why ASP.net
6.2 Evolution of ASP.net
6.3 Features of ASP.net
6.4 Difference between ASP and ASP.net
7 Internet information service(IIS)
8 Working with ASP.net Applications
8.1 Why ASP.net
8.2 Evolution of ASP.net
ASP.net
3
8.3 Features of ASP.net
8.4 Difference between ASP and ASP.net


9 Coding Techniques in ASP.net
9.1 Code inline model
9.2 Code behind model
10 Controls in ASP.net
10.1 client side controls
10.2 silverside controls
10.2.1 HTML server controls
10.2.2 Web server controls
10.2.3 Common properties with webserver controls
10.3 Different Types of controls in ASP.net
10.3.1 Standard controls and examples
10.3.1.1 Label
10.3.1.2 TextBox with Example
10.3.1.3 CheckBox with Example
10.3.2 Redirecting The user Request
10.3.2.1 Hyperlink Button with Example
10.3.2.2 Link Button with Example
10.3.2.3 Image Button with Example
10.3.2.4 Differences b/n button controls
10.3.2.5 Response. Redirect
10.3.2.6 Server. Transfer
10.3.3 Button controls
10.3.3.1 Events with Button Controls
10.3.3.2 Click Event with Example
10.3.3.3 Command Event with Example
10.3.4 Listing Controls
10.3.4.1 ListBox
10.3.4.2 DropDownList
10.3.4.3 RadioButtonList
10.3.4.4 CheckBoxList
10.3.4.5 Panel control
11 Validation Controls
11.1 Difference b/n client side and server side validation
11.2 Different Types of validation controls
11.2.1 Required Field validator with Example
11.2.2 Range validator with Example
11.2.3 Regular Expression Validator with Example
11.2.4 Compare validator with Example
11.2.5 Validation Summary with Example
11.2.6 Custom validator with Example
ASP.net
4
12 Navigation Controls
12.1 Menu Controls with Example
12.2 Treeview Controls with Example
13 Calendar control with example
14 ADO.net
14.1 introduction to ADO.net
14.1.1 I-layered approach
14.1.2 II-layered approach
14.1.3 III-layered approach
14.2 ADO vs ADO.net
14.3 ADO.net architecture diagram
14.4 Connection oriented architecture
14.4.1 Data Providers in ADO.net
14.4.2 Objects in ADO.net
14.4.3 Steps to work with connection architecture
14.4.4 Example with Connection object
14.4.5 Command object
14.4.6 Steps to work with command object
14.4.7 Differences between Execute methods
14.4.8 Example with command object to delete .
14.4.9 Example with insert, update and delete
14.4.10 disadvantages with connection oriented.
14.5 Disconnected Architecture
14.5.1 Disconnected Data cycle
14.5.2 Dataset
14.5.2.1 Steps to work with Dataset
14.6 Data Bound Controls
14.6.1 Templates
14.6.2 Types Of Data Bound Controls
14.6.2.1 Repeater Control
14.6.2.2 Data list Control
14.6.2.3 Grid view Control
14.7 Repeater Control
14.7.1 Designing Repeater Control in Table
14.8 Data List Control
14.8.1 Events associated with Data List Control
14.8.2 Displaying Data in Datalist Control
14.8.3 Deleting with Data List Control
14.8.4 Editing with Data List Control
14.9 Grid View Controls
14.9.1 Displaying Data in GridView
14.9.2 Paging with GridView
14.9.3 Check Boxes with Grid View
14.9.4 Radio Buttons with Gridview
ASP.net
5





15 Ad Rotator Control
16 CSS in ASP.net
17 Themes and Skins
18 Master Pages
19 State Management in ASP.net
15.1 View state
15.2 URL encoding
15.3 Cookies
15.4 Sessions
15.5 Application
15.6 Caching
15.7 Query String
20 500 Frequently asked questions


























ASP.net
6

MICROSOFT.NET

It is a collection of languages, technologies, frameworks, tools, libraries etc
Integrated one environment which enables to communicate device to device
or application to application.
It provides one environment for developing different applications rapidly and
efficiently.
MICROSOFT DEVELOPMENT TECHNOLOGY
OLE TECHNOLOGY: it is used for multiple application access by
creating link between the application

COM TECHNOLOGY: it is used to create the communication between
the modules
MS.NET: later they upgraded these technologies in new environment
called as MS.NET

VERSIONS OF .NET:

MS.NET 1.0:-introduced in the year 2000 (beta)
MS.NET 1.0:-introduced in the year 2002 (alpha)
MS.NET 1.1:-introduced in the year 2003 (alpha)
MS.NET 2.0:-introduced in the year 2004 (beta )
MS.NET 2.0:-introduced in the year 2005 (alpha)
MS.NET 3.0
MS.NET 3.5

Note: Microsoft has given a statement that some new frameworks are

Released under winfx named later renamed as Microsoft.net3.0

Features according to versions of .net:
MS.net1.0 many application support
Separate installation
Crystal report installation
Mobile application
MS.net1.1 Crystal report and Mobile application are inbuilt

MS.net2.0 64-bit compatibility
Along SQLserver Enterprise edition Generic
Classes,Generic methods, nullable types etc



ASP.net
7
.NET FRAMEWORK
It is the layer between
Application and OS
It consists of
1. CLR
2. BCL
Tools:-compiler
Interpreter
Debugger
Assembler and
disassembler
.NET PRODUCTS
MSVisual studio editor
MS Simulator
.NET Servers
MSSQL Server
BizTalk server
IIS
Mobile IIS
Exchange server
Internet Security Server
Etc..
.NET Services
Passport service
Calendar service
Contact Service
Alert Service
Web service
Etc.
MICROSOFT.NET

1).NET FRAMEWORK: it protects the OS and enables the application
execution
CLR: it is the runtime environment used to execute all the .net
applications.
It applies security, memory management and monitors the execution of
the program.
Base Class Libraries: it provides some predefined functionality which can
be reused for developing the application in .net environment. Nearly 4000
predefined Classes are provided for developing the applications

2) MICROSOFT PRODUCTS: MS has provided its products for faster
development
Of applications and testing of the applications
a. MS VISUAL STUDIO EDITOR
b. POCKET PC SIMULATOR


ASP.net
8


MS VISUAL STUDIO EDITOR: it is an integrated development
environment for developing different types of applications i.e. execution,
debugging, designing etc
POCKET PC SIMULATOR: it is a special type of environment used for
testing mobiles and smart pc applications
3) .NET SERVICES: a service is a back roundly running program which is
used for automatic the process
Ex: passport, alert, contact, address, web service, calendar etc..
4) .NET SERVERS: MS has provided nearly 14 servers support like
a). IIS :which acts as the webserver for ASP.net web application
b).MOBILE IIS: which acts as a webserver for mobile application
c).MS SQLSERVER:it acts as a database for storing information
permanently
d).ISS: Internet security server it is used for applying security for ASP.net
applications
e).BISTALK SERVER: it is used to store the information in XML format
f).EXCHANGE SERVER: it is used for exchanging mails
g).ECOMMERCE: it is used for online banking etc.

5).NET TOOLS: it is used for compiling and executing or checking the
structure of files by using built-in tools like
Compilers,interpreters,debuggers,assemblers,disassemblers etc
6).NET LANGUAGES: it supports different types of languages to group all
the programmers in the world and works under one platform called MS.NET
.NET1.0 supports 17 languages
.NET1.1 supports 21 languages
.NET2.0 supports 32 languages
Ex: MICROSOFT LANGUAGES
VB.NET
C#.NET
VISUAL C++.NET
VISUALJ#.NET
THIRD PARTY LANGUAGES
COBOL.NET
PASCAL.NET
EFFIEL.NET
MANAGED C++.NET
JSCRIPT.NET
PERL.NET
PYTHON.NET etc.


ASP.net
9
7).NET TECHNOLOGIES: a technology is the convergence of more than
one language for developing different applications
Ex: ASP.NET is used for web applications
ADO.NET is used for database handling
WEBSERVICES are used for complete distributed applications


ARCHITECTURE OF MS.net




Application layer
Translating layer
Base class layer
C#.net
Web
applicat
Vb.net J#.net
Windows
applicat
Mobile web
applicat
Service
applicat
Data IO Security
XML Threading
Memory
management
CLR
Security
checking
Monitoring
The
Life cycle
OS
ARCHITECTURE OF MS.NET

APPLICATION LAYER: This layer is used for presenting the
application by developing the front ends. This layer provides some
collection of languages and application from which we can choose and
develop the application

BASECLASSLIBRARIES: This layer provides some predefined
functionalities which are used by application layer for developing the
application

ASP.net
10
TRANSLATING LAYER: This layer is used to convert your application to OS
understandable language by managing the memory, checking the security
and monitoring the program



LIFE CYCLE EXECUTION OF .NET APPLICATION

.net application---- compilation---- IL--- CLR--- OS
IL (intermediate language):it is the compiled format of any .net program which is
OS independent.
It can be called as MSIL, CIL, and assembly
IL format is of two types
.dll format: it is reusable format it is not executable format
.exe format: it is executable format it is not reusable
ILARCHETECTURE:it consists of 4 parts and 1 wrapper to describe itself
METADATA
CODE
RESOURCE
MANIFEST
PE WRAPPER

METADATA: it is used to describe the data of the IL file i.e. it provides the
structure of the program like class names, method names etc
CODE: it provides the actual instructions of IL file
RESOURCE: it provides the additional information like images, cursors, icons et
ASP.net
11
MANIFEST: it provides documentary information like product name, company
name, and version no, strong name etc.
PE WRAPPER: it contains some executable format which invokes the CLR.
Note: if you want to view the complete IL file then ILDASM.exe

ILDASM.exe: it is a build-in tool of .net used to show the wrapper file or IL file



CLR
ILLOADER
ACCESS CONTROLER
CAS RBS
CTS CLS
MEMORY MANAGEMENT
JIT COMPILER

CLR is common language runtime
It is a runtime environment used to convert IL file to native OS
understandable format and also provides some services like memory
management, type checking, monitoring the lifecycle of the program
etc
It is the heart and soul of .net frame work used to perform every
operation in .net
It consists of
IL loader
Access controllers
Memory management
Jit compiler



ASP.net
12


IL LOADER: it is used to load the complete IL file in to the clr.

Access Controller: it is used to check the security privileges of IL file
Different types of access controllers are

1. CTS:common type system :it provides common data types for all .net
languages and checks whether IL file is using those data types are not
2. CLS:common language specification: it provides some common rules
for all .net languages and check whether IL file is following those rules
are not
3. CAS:code access security: it checks whether the code is executing on
the O.S and if it is invalid code it displays error message
4. RBS: role based security: it checks whether the login user is valid or
invalid and it provides permissions for accessing and executing .net
applications. by default administrator have the privileges for accessing
.net applications
Memory management: it look after the memory allocation and
memory
Deal location .it uses GIGO process for memory management.
Note: Managed applications: the applications whose memory
management will look after by runtime environment i.e. by CLR
Without any user interface is called managed application.
JIT compiler: it is used for converting IL code in to native machine
understandable format by compiling it
Types of compilers:
PreJIT: it is used to convert the complete IL code into native machine
understandable format
Standard JIT: it is used to convert only the called method to
machine understandable format use it and remove it from the memory
ASP.net
13
Echno JIT: it is used to convert the called method to machine
understandable format use it and maintain the copy in the temporary
location for the next request


HYPER TEXT MARK UP LANGUAGE (HTML)

Web applications
Dev WebPages
Static webpage Dynamic webpage
HTML
PHOTOSHOP
FLASH
client side Server side
DHTML
ASP
ASP.NET
ISP
SERVELETS









ASP.net
14
Static webpage: a webpage whose output is static with diff request is
called as static webpage which can be generated by using
HTML,PHOTOSHOP,FLASH.
Dynamic webpage: a webpage which provides different outputs for diff
clients request is called dynamic webpage.
Client side dynamic webpage: a webpage whose o/p changes with
every request to provide new look and animated affects which can be
generated by DHTML concepts
Server side dynamic webpage: the webpage which generates diff o/p
by processing every request on server machine which can be generated
by some technologies like ASP, ASP.NET, JSP, SERVELETS etc.



HTML: Hyper text markup language
It is used for dev static WebPages and it is one of the markup language
Markup language: a language which is used for concentrating on the structure
and formatting of the document to display.
SML: specific markup language: a markup language which is specific for an
application or OS which is not compatible with other application or OS
Ex:RTF,HTML
GML:Generalised markup language: it is used to provide generalized format
which can be understand by any device or os
Ex:XML
Features of HTML:
It is free form language (case insensitive language)
It is space insensitive language
It is line insensitive language
It is error free language
It is tag oriented language
Tag is a command enclosed in angular braces



ASP.net
15

Syn :<cmd>
Tag contains two elements starting element and ending element
Starting element <command>
Ending element </command>
Every tag in HTML is predefined and optional
Tags are of two types container tags and non container tags
The tag which contains both starting element and ending elements is
called container tags
Ex: <html> </html>
<p></p>etc.
Tags which provides only starting elements are called non container
tags
Ex :<br>break line
<hr>horizontal ruler etc
TAG REFERENCES

Different types of tag references are
1. BASIC TAG
2. TEXT FORMATING TAG
3. LINK TAG
4. LIST TAG
5. FRAME TAG
6. TABLE TAG
7. FORM TAG
8. MULTIMEDIA TAG



ASP.net
16



Basic tags: these tags will provide the structure of the document
Ex:
<html>
<head>
<title>HELLO</title>
WELCOME TO HTML
</head>
<body bgcolor="#CCCCCC"
background="F:\WALLPAPERS\Ganesh.jpg">
THIS IS HTML DOCUMENT
THIS IS MY FIRST PROGRAM
</body>
</html>
Link tag: it is used for linking one document with another document
Or different parts of same document
Hyper link: it is used for linking two documents

h1
F1.html
F2.html
link

Cross link: it is used for linking same document different paths
Anchor tag is used for linking
ASP.net
17


Ex for hyper link
<html>
<head>
<title>HELLO</title>
WELCOME TO HTML
</head>
<body bgcolor="cyan" background="F:\WALLPAPERS\All
Pictures\14.jpg" >
THIS IS HTML DOCUMENT
<a href="E:\TECHNOLOGIES\6pm\HTML\basictag.html">
click here to show basic tag
</a>

</body></html>

Text formatting tags: these tags are used to formatting the text by
applying font style, size and font names etc
Ex:
<B> BOLD
<I> ITALIC
<U> UNDERLINE
<SMALL> SMALL FONT
<BIG> Big FONT
<STRONG>
<S><SUP><SUB>
<FONT>
<HR><BR><P>
<PRE>
ASP.net
18

LIST TAGS:
It is used to display the information in bulleted format or numbered format
etc..
<ul> unordered list
<ol >ordered list
<li >list item
<dd>data definition
<dl>data list
<dt >data table



Ex for List tags


source code:

<Html>
<h1>
MEMORY
<UL TYPE="SQUARE">
<LI>PRIMARY MEMORY
<OL TYPE="1">
<LI>RAM
<LI>ROM
</OL>
<LI>SECONDARY MEMORY
<OL TYPE="I">
ASP.net
19
<LI>HARD DISC
<LI>COMPACT DISC
</OL>
</UL>
</H1>
</html>

MULTIMEDIA TAGS: this tag is used to display the images on the text
<IMG>TAG:<IMG SRC=PATH OF IMAGE DYNSRC=PATH OF
MEDIA FILE WIDTH=NO BORDER=NO>
<MARQUEE>=SCROLLING
<MARQUEE>
<H1> WELCOME</H1>
</MARQUEE>
<MARQUEE> IT IS USED TO PROVIDE SOME ANIMATION AFFECTS
PROPERTIES:
<MARQUEE DIRECTION= RIGHT
LEFT
UP
DOWN
BEHAVIOUR=ALTERNATE
SCROLL
LOOP=SOME NO
SCROLL AMOUNT=MILLISEC SCROLLDELAY=MILLISEC
BG COLOR=SOME COLOR
WIDTH=SOMENO HT=SOME NO BORDER=SOME NO>



ASP.net
20

Ex for multi media tag:




Source code:

<HTML>
<IMG SRC="D:\KANNA PICS\SP_A0101.jpg"
WIDTH=200HT=50 BORDER=5>
<MARQUEE DIRECTION="left" BEHAVIOUR="alternate" LOOP="-1"
SCROLLAMOUNT=100 SCROLLDELAY=1000 BGCOLOR="RED">
<H1>WELCOME</H1>
</MARQUEE>
</HTML>






ASP.net
21
Font tags:
Syn :<font face=value size=value color=value>
</font>
Font tags:
Syn: <font face=value size=value color=value>
</font>
Arial
Monotype Corsiva
Times New Roman
1 least size
2
3 default size
4
5
6
7 highest size

Example with font tags






ASP.net
22
View source

<Html>
<Body>
<font face="ariel" size="10" color="red">
HI KANNABABU
</FONT>
<BR><BR><BR>
<FONT FACE="TAHONA" SIZE="7" COLOR="BLUE">
HTML IS MARKUP LANGUAGE
<BR><BR><BR>
<FONT FACE="VERDANA" SIZE="5" COLOR="GREEN">
HTML SUPPORTS FONT TAGS
</FONT>
</body>
</html>

FRAME TAGS:
These tags are used to divide the webpage into different webpartsFrameset tags
has two optional attributes
ROWS ATTRIBUTES: it is used to divide the webpage in to horizontal parts
COLUMNS ATTRIBUTE: it is used to divide the webpage into vertical parts
Each part of the webpage is known as a frame
Every frame should be identified using NAME attribute
To assign the name to a frame frameset tag contains a sub tag known as
frame
It is a note after displaying webpage
There is no direct method to display the contents within a frame directly
any matter we want to display within aframe we will store in a html file and
attach this HTML file to the frame using src attribute
Frame names are case sensitive




ASP.net
23

Ex with Frame Tags





View source:

<? Code for frame.html...>
<HTML>
<FRAMESET ROWS="30%,70%">
<FRAME NAME="a" src="kanna.html">
<FRAMESET cols="25%, 75%">
<FRAME NAME="b" src="link.html">
<FRAME NAME="c" src="home.html">
</FRAMESET>
</FRAMESET>
</HTML>


ASP.net
24


Form Tags:

FORM TAGS: it is used to design some webpage by placing some controls
It used to provide a container where we can place some controls like
Textboxes, buttons, RadioButton,etc.
<Form>
Properties: method=get\post
name=some text
action=some path
<input type=text>
Name=some path
Value=number
Read-only
Disabled
Textbox is the data entry control
Password textbox:it is used to accept some text but hides the text with
some symbol like *
Properties are same as textbox
Multiline textbox: it is used for accepting multiple lines of text
<text area>
Name=some text
Value=some text
Rows=some no
Columns=some no
Note: text area tag is noncontainer tag




ASP.net
25


Radio button control: this control is used for providing a group of options
from which we can select anyone.
To group a set of radio buttons provide common names
Syn: <input type=radio name=some text>
Checkbox control: it is used for selecting and deselecting an item
Syn: <input type=checkbox name=some text>
Dropdown list :it is used for providing some list of items from which we
can select any one in a dropdown fashion.
Syn: <select name=some text>
<option selected>..


</select>
Listing Controls: it provides list of items in a box format from which we can
select single or multiple items by holding control key
Syn: <select name=some text size=no multiple>
<option selected>..


</select>











ASP.net
26

EX with Form tags




View source:

<HTML>
<HEAD>
<H1 ALIGN="CENTER">KANNA TECHNOLOGIES </H1>
<H2 ALIGN="CENTER"> HYDERABAD </H2>
</HEAD>
<HR COLOR="BLUE">
<BODY>
<B><U> <FONT SIZE="4" COLOR="RED">
PERSONAL DETAILS FORM </FONT></U></B>
<FORM NAME="F1"
action="" method=get>
<table align="center">
<tr>
<td>ENTER YOUR NAME : </td>
<td><INPUT TYPE="TEXT" NAME="T1"></td>
</tr>
<tr>
<td>ENTER USER NAME :</td>
<td><INPUT TYPE="TEXT" NAME="T2"></td>
</tr><tr>
<td>ENTER PASSWORD :</td>
ASP.net
27


<td><INPUT TYPE="PASSWORD" NAME="T3"></td>
<tr><BR><tr>
<td>SELECT GENDER : </td>
<td><INPUT TYPE="RADIO"
NAME="GENDER" VALUE="MALE">MALE
<INPUT TYPE="RADIO" NAME="GENDER"
VALUE="FEMALE"> FEMALE </td><BR>
</tr><tr>
<td>SELECT QUALIFICATION </td>
<td><SELECT NAME="CB1">
<OPTION> SSC </OPTION>
<OPTION> 10+2 </OPTION>
<OPTION> DEGREE</OPTION>
<OPTION> PG </OPTION>
<OPTION> OTHERS </OPTION>
</SELECT></td>
</tr>
<BR><tr><td>SELECT HOBBIES :</td><nbsp>
<td><INPUT TYPE="CHECKBOX" NAME="C1" VALUE="DANCING"> DANCING
<INPUT TYPE="CHECKBOX" NAME="C2" VALUE="PLAYING"> PLAYING
<INPUT TYPE="CHECKBOX" NAME="C3" VALUE="BROWSING"> BROWSING
<INPUT TYPE="CHECKBOX" NAME="C4" VALUE="CHATTING"> CHATTING
</td></tr>
<tr><td>DESCRIBE YOUR SELF :</td>
<td> <TEXTAREA NAME="TA1" ROWS="5" COLS="10"> </TEXTAREA> </td>

</tr><BR><tr><td><INPUT TYPE="SUBMIT" NAME="B1"
VALUE="SUBMIT"></td>
<td><INPUT TYPE="RESET" NAME="B2"
VALUE="RESET"></td></tr>
</FORM>
</BODY>
</HTML>









ASP.net
28
BUTTON CONTROLS

RESET BUTTON: it is used for providing a webpage with default
settings
Syn :<input type=reset>
Submit Button: it is used for submitting the page to the specified
path mentioned in the action attribute of form tag
Syn :<input type=submit value=submit>
Reset Button: this tag is used for invoking some functions of scripting
languages
Syn :<input type=button value=click>



























ASP.net
29



SCRIPTING LANGUAGES:


SCRIPTING LANGUAGES: these are used for dynamic client side web
applications
These are the interpreted languages where the execution is on the
client machine
Different types of scripting languages
ECMA:Europeon computer manufacturer association develop first
scripting language for computer manufacturer architecture
LIVE SCRIPT: which was later renamed as JavaScript? it is product of
sun Microsystems
Vb script: it is developed by Microsoft for macro programming in MS
office package
Jscript:it is product of Microsoft resembles JavaScript
Pearl script
Python script
Anaconda script etc.
Features of scripting languages: these are used for providing client
side calculations
Provides animations
Supports validations by accepting proper input from the user
It also enables for database and file handling by depending on com
components




ASP.net
30



Java script
JavaScript is the premier client-side scripting language used
today on the Web.
Its widely used in tasks ranging from the validation of form data
to the creation of complex user interfaces.
JavaScript can be used to manipulate the very markup in the
documents in which it is contained.
It is client side scripting programming language
Java script code can be written in any text editor
JavaScript code can be executed in any browser
It is case sensitive programming language
To execute JavaScript code browser contains scripting language
parser
Parser is similar to interpreter
It is platform independent
JavaScript code is written in between <script ></script>tag
Java script code is developed by Netscape company
Java script is object based programming language
Java script does not contain any predefined data types
HTML tags can be integrated within the JavaScript code






ASP.net
31



To add JavaScript to your webpage place the tag
<script language=JavaScript>
Ex:
<html>
<script Language=JavaScript>
Document. Write (welcome)
</script>
</html>

VARIBLES IN JAVASCRIPT
JavaScript doesnt support any predefined data types thats why
JavaScript is known as loosely typed programming language
To declare variable in JavaScript we use 2 methods
Variable=value
Var variable=value

Ex:
S=welcome var s=welcome
S=10 var s=10
S=10.5 var s=10.5



S is global variable s is local variable
Variable names are case sensitive
There is no limit for data to store in a variable we can store up to 32
bytes any amount of data

Working with variables
<Html>
<script Language=JavaScript>
S=<h1>WELCOME</h1> or s=welcome
document.write(s)
document.write(<h1+s+</h1>)
</script>
</html>

ASP.net
32


Functions in javascript:

Prompt function:
It is used to accept any data from the user.
Variable=prompt (message)
Ex:
A=prompt (enter first number)
Return type of prompt is string

Eval function:
This is used to convert any number from string form to number form
Ex:
Eval (10)
Eval (10.5)

Alert function:
It is used to display the message in dialogue box with ok button

WORKING WITH JAVASCRIPT
Function: a function is a reusable piece of code within the program to
perform the required task or operation.
To define any function in JavaScript we use function keyword.
Syntax:
Function function name ([args list])
{
[return type]
}
ASP.net
33
In JavaScript it is always better or advisable to write function definition
within the head part of the html and to call the function from the body
part of the html.
Example for a function without passing arguments and without
return value
<html>
<head>
<script language="JavaScript">
function Add()
{
var a=10;b=20
c=a+b
document.write("<font size=5>sum is :"+c+"</font>")
}
</script>
</head>
<body>
<script language="JavaScript">
Add()
</script></body></html>

Function overloading: assigning additional work to the function
other than the existing work is called function overloading
In any programming language we overload a function in two
situations.
1. When no of arguments are changed
2. When data types of arguments are changed

When no of arguments are changed:
Ex: Add(int a,int b)
{
..

}
We can call the function by passing 2 args like Add(10,20)

If we want to pass 3 args like Add(10,20,30) then it is not possible
then we overload the function like
Add(int a,int b,int c)
{
..
}
ASP.net
34

When data types of arguments are changed:

When data types of args are changed
If we take function like
Add(int a,int b)
{
..

}
We can call the function by passing 2 args like Add(10,20) but if we
pass diff erent data types values like Add(10.5,20) then it is not
possible and in this case we overload our function like
Add (float a, int b)
{
..
.
}
In JavaScript it is not req to overload a function when no of args are
changed or when data types of args are changed in boeh the cases we can
use the same function




ASP.net
35



Objects in java script
String: it provides various properties and functions that will allow us to
work with various strings
Functions with string object
to Lowercase().>converts the string into lower case letters
to Uppercase()..> converts the string into upper case letters
subString(Index)..>return the remaining part of the string from
the given index
subString(Index, Length)>return the given length of characters from
the given index value
charAt(Index)...>return the character present at the given index
charCodeAt(Index)..>returns the ASCII value of the character
present at the given index
index Of(character)...>returns the index value of the character
present at the given index
split(split string).>separates the split string from the given
string
bold()>applies the bold format for the given string
Italics().>applies the italic format for the given string
ASP.net
36
Strike().>applies the strikethrough for the given
string
link(urladdress)>creates a hyperlink to the given string
with target as given url

Ex: S= TECHNOLOGIES
S.toLowercase() ..>
S.toUppercase().>
S.substring(7).>
S.substring(0,7)..>
S.CharAt(1)..>
S.CharcodeAt(1)..>
S.indexof(a)..>
S.indexof(m,2)..>
S.Split(TECHNOLOGIES)>
S.link(www.gmail.com)>

Document object: it represents the work area within the browser
window
Properties: fgColor
bgColor
fgColor:this property is used to change the content color within the
browser window
Default fgColor is black
bgColor:this property is used to change the background color of the
document
Usage document.fgColor=color value
document.fgColor=blue
document.bgColor=color value
document.bgColor=yellow
Methods with document object:
1. Write method within one argument
Write (message)
This method is used to print the required message within the document
Ex: document.write (welcome)
Ex with document object








ASP.net
37





DYNAMIC HYPERTEXT MARKUP LANGUAGE

It is used for developing dynamic client side web applications
The extension of this application must be saved with .htm or .html
extension
The internet explorer from 4.0 supports DHTML
DHTML is a combination of simple text editor HTML tags CSS and
scripting languages
cascade style sheet(CSS): it is used for applying some extra
formatting features on existing HTML tags
Style represents appearance of a webpage
Style sheet is group of styles
Css provides some list of property names and values
Syntax:
Property name: Property value
Types of Style Sheets:
1. Inline Style sheet
2. Embedded Style sheet
3. External Style sheet
4. Imported Style sheet







ASP.net
38


Inline Style sheet
The style sheet whose style definition is placed under tag
declaration using style attribute is called as inline style sheet.
Syntax:
<tag name style=property name: property value; property name:
property value>

Example



View source
<Html>
<h1 style="color: red; font-family:'verdana'; font-weight: bolder; text-align:
center">
Welcome to css
</h1>
<input type=text
style="font-size:11;color:blue;border-color:maroon;border-width:5;border-
style:dotted">
</html>
ASP.net
39
Embedded style sheet: the style sheet whose style definition is placed
under style tag which automatically apply the styles on the html tags used in
the program
Syntax :< style type=text/css>
..

..
</style>
Embedded style sheets are of three types
1. Tag as a selector
2. Id as a selector
3. Class as selector
Tag as a selector: it is used for grouping the similar tags and
applying the style definition
Syn:<style type=text/css>
tag name{

..
}

Example:


View source:

<html>
<style type=text/css>

h1{
background-color:khaki;color:red;
}
h3{
ASP.net
40
background-color:blue;color:green;
}

</style>
<h1>CASCADEING STYLE SHEETS</h1>
<h1>CASCADEING STYLE SHEETS</h1>
<h3>CASCADEING STYLE SHEETS</h3>
<h2>CASCADEING STYLE SHEETS</h2>
</html>

Class as selector: it is used for grouping controls by poviding
common class attribute values and its style definition should
preceed with a period(.)
Syntax:
<style type=text/css>
.t{

.
</style>
<tag name class=t>
}
Example:







ASP.net
41

View source:
<html>
<style type=text/css>
input{
font-size:10;
}
.t{
background-color:yellow
}
</style>
<center>
<h1>LOGIN FORM</h1>
<h2>
<form>
Enter user name:<input type=text class=t>
<br><br>
Enter password:<input type=password >
<br><br>
<input type=button value=signin class=t>
</form>
</h2>
</center>
</html>





ASP.net
42

Id as a selector: this type of embedded style sheet is used for
grouping some set of controls by providing common id
Syntax:
<style type=text/css>
#id{

.
</style>
<tag name id=some id>
}
Example








ASP.net
43


View source:
<html>
<style type=text/css>
#p{
font-size:30;
}
#p1{
background-color:green;
}
#p2{
background-color:lavender;
}
</style>
<p id=p1>this is id selector</p>
<p id=p2>this is id selector</p>
<p id=p1>this is id selector</p>
<p id=p>this is id selector</p></html>

Imported style sheet: it is used for importing one css program program
into another css program and also import one css program into html
program.
Imported style sheet works with a notation called as @import
Syn:@import url(path of css);
This notation is used within style tag under under .html program
Example:






ASP.net
44

View source:
Code for p1.html
<html>
<link rel=style sheet href="style1.css">
<h1>EXTERNAL STYLE SHEET</h1>
<p>welcome to technologies</p>
</html>

Code for style1.css

h1, h2,h3,h4,h5,h6{
Color: red;
}
p{

background-color: pink;
}


Example2 with imported style sheet






ASP.net
45



View source:

Code for p2.html
<html>
<style type=text/css>
@import url('style3.css');
</style>
<h1>EXTERNAL STYLE SHEET</h1>
<p>welcome to technologies</p>
</html>

Code for style3.css

@import url('style2.css');
p{
background-color:pink;
font-size:30;
font-family:arial;
}

Code for style3.css

h1,h2,h3,h4,h5,h6
{
color:red;
}


ASP.net
46
ASP. Net

WHY ASP. Net:


Originally web development started with HTML but the pages designed
using HTML are static WebPages because HTML is used only for
designing the WebPages
Html cannot be used to perform the validations and to execute events
In the below figure we can design the complete webpage using html
but we cannot perform The validations like Whether user entered
username, password or not and events like when user clicks on
button,What to do etc.
To overcome this drawback we got DHTML
DHTML:it is the combination of HTML and client side

Enter user name
Enter password
login cancel



Scripting language
Client side scripting code:
In the above example if user is not entering username and password we
should not submit the request to the server so to check user entered
username and password etc code should be executed within the browser
only
Code that is executed within the browser only. code that is executed
within the browser window to perform the events and validations is
known as client side scripting code.
Programming language that is used to write client side scripting code is
known as client side scripting language
Ex: javascript, vbscript, jscript etc.




ASP.net
47


Server side technology: in the above example when user enters
username and password and clicks on login button then we should
submit the webpage
To the server at server side code should be executed to check whether
Username and password are correct or not code that is executed at
The Server side is known
As server side scripting code
Technologies that we use to write server side scripting code are known
as server side technologies.
Ex: ASP, ASP.net, JSP
ASP. net:

ASP. net is a server side technology or web technology used to build
interactive web applications
It is a next generation technology of Microsoft which is used to provide
a new way for developing server side web applications .it is added with
a dynamic nature along with some features taken from different
technologies and languages
It is a collection of html (xhtml) ,scripting languages, any one .net
supportable language .
Evolution of ASP. net: the evolution has started a decay ago by Tim
Berne lee who has established http protocol used for communication.
Based on it the professional have developed html and xml for
webpage development and data transformation. Many
companies like microsoft,sunmicrosystems, IBM was struggling to add
dynamic nature in the WebPages and finally Microsoft has released its
first technology for dynamic server side web application called as ASP
in the year 1996.
1996 ASP 1.0
ASP 2.0
ASP 2k
ASP 3.0
ASP. net 1.0 ..>2002 (alpha)
ASP. net 1.0 ..>2003 (beta)
ASP.net 1.1 .>2003 (alpha)
ASP.net2.0 ..> 2004 (beta)
ASP.net2.0 > 2005 (alpha)
ASP.net3.0 ..>
ASP.net3.5 .> 2008 (beta)


ASP.net
48
Asp was a powerful technology but failed in the internet market due to
some problems like Interpreted execution which is very slow in process
It is a loosely typed language which does not support any data type
It uses difficult configuration settings for using the components to
develop advanced web applications
ASP applications crashes frequently due to unpredictable error becoz
it doesnt have a proper structured exception handling or error
handling
Asp is not a object oriented technology so it depends on some other
programming language for any component requirement
To overcome these problems Microsoft has provided a new technology
under .net called as ASP. Net



FEATURES OF ASP. Net

o ASP. net is the compiled technology but not interpreted due to
this application execution will be faster and increases the
performance of the application.
o ASP. net supports multiple languages of .net it makes
component development easy and it will be OS independent due
to IL format.
o Note:ASP1.1 compiles complete web applications at once .only
on language can be used.
o ASP2.0 compiles complete web application in page by page
pattern. so multiple languages can be used
o .Multidevice or multibrowser support: ASP. net supports
device detection due to which ASP. net Supports device
detection due to which ASP. net can develop diff types o/p for
different types of browsers.
o ASP. net uses easy way for configuration and deployment of the
application.ASP.net maintains all its configuration settings in
an xml based file which automatically configures IIS before
executing the application and it uses the easy way for
deployment by developing a setup file
o ASP. net is integrated under .net environment ASP. net can use
all the base class libraries of .net framework for developing the
web based applications
o ASP. net 1.1 class libraries are added with new class libraries
and introduced in ASP. net 2.0
o ASP. net applications run under .net runtime environment i.e.
CLR
ASP.net
49
o ASP. net 2.0 important feature for executing the web based
application by using some concepts of the CLR like
o MEMORY MANAGEMENT:CLR will allocates memory for every
user and removes its object when it is not accessible through
garbage collector
o TYPE CASTING: checking the data types conversions and
providing the functionalities required for execution.
o MULTITHREADING: as web applications are multi users CLR has
to identify every client and allocate separate memory for it which
is possible only through Threading
o ASP. net has introduced nearly 50 new controls for developing
advanced web application with easy and efficient way without
writing any code
o ASP. net 2.0 has provided a new technique for simplifying the
application designing by introducing master pages ,themes, and
skins
o ASP. net provides structural error handling ,tracing, and
debugging of the application to avoid the unpredictable
termination of the program.

Differences between ASP and ASP.net:




s.no ASP ASP. Net
1. It is object based technology It is object oriented
technology
2. It is loosely typed language It is strongly typed language
3. ASP is bounded with scripting
language
ASP.net is language
independent which supports
scripting language and .net
language
4. It uses difficult configuration on IIS ASP.net maintains is req
configuration in an xml file
5. It supports three web servers for
execution IIS,PEARL,PERSONAL web
server
ASP.net supports only IIS
6. It depends on HTML controls It provides its own controls
7. It does not supports structured error
handling
It supports structured error
handling
ASP.net
50


About IIS

Webserver:it is a tool which is used to
One or more websites within it
Takes the request from the client process the request and sends the
result back to the client
Ex:for windows OS
Personal web server
Peers web server we cannot run ASP. net
IIS used for ASP. net
For UNIX os
Tomcat
Apache
IIS: internet information System: it will automatically come along with
O.S
To check whether IIS is present in the system or not within the system
Click on start
If a window is opened named IIS console then IIS is present within the
machine
If any error window appears then IIS is not present in the machine
Installing the IIS if not present:
Go to run prompt
Type appwiz.cpl
Click on Add windows components
Check IIS and put O.S cd and follow the steps
Order of installation of software:
O.S
IIS
Database (sql server/oracle)
VS. net 2005
If IIS is installed after visual Studio.NET then ASP. net applications will
not run properly becoz ASP. net is not registered at IIS


To reinstall the ASP. net and to register at IIS we have a separate tool as
8. It depends on com tech for database
and file handling
It uses .net framework class
libraries for database and file
handling and com
components
9. It is interpreted technology It is compiled technology
10. .asp .aspx
ASP.net
51
aspnet-regIIS-I
To work with this tool use the following steps
Click start click on programs click on MS.NET framework sdkv2.0
Click on sdk cmd prompt type aspnet_regIIS-I
Note: this will reinstall asp.net s/w and will register asp.net with IIS
type IISreset this will stop the iis and restarts iis



Working with ASP. net applications:

Open visual studio click on file click on new click on website


Visual studio editor-2008
Open dotnet in by typing devenv in command prompt



ASP.net
52
To develop ASP.net webforms we can develop in two editors
Simple text editoe
Visual studio editor
Simple text editor:when we develop a webform in simple text editor
we can write userinterface and code but the configuration settings are
by default considered from a predefined file machine.config
It is available in
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\machine.config




Select ASP. net website template select the programming language with
C#.net
Select the location as HTTP type the website
name(http://localhost/websitename) ok
Then automatically different windows will open
Design window
Source code window
Business logic window
ASP.net
53
Solution explorer window
Server explorer window
Tool box
Property window
Error List



When we creates any website in ASP. net by default visual Studio.NET
will create the directories in two locations
C:\inetpun\wwwroot(disk location)
At IIS
The directory which is created at this location is called as physical
location
All the original code files are stored in this location
The directory created at IIS is known as virtual directory
This directory will contain all the files with the link created to the
physical directory files
Creating virtual directory or alias is to provide security to the original
files.








ASP.net
54


LIFE CYCLE EXECUTION OF ASP.net





Life cycle execution of ASP .net application
client
http://localhost/code1.aspx
IIS Inetinfo.exe
aspnet_isapi.dll
aspnet_wp.exe
request
O/p display
process
o/p
CLR
wp.exe-workprocess
http pipe lines
ASP. net work process
server



ASP.net
55



When a client gives the url the request is forwarded to the specified
web server i.e. IIS
IIS forward the request to inetinfo.exe file it checks the type of the
request and forward the request to the respective engines
If the request is ASP. net then it forward the request to ASPnet-
isapi.dll this file is mapped on IIS to identify asp. net request
location i.e. virtual directory
ASPnet-isapi.dll is forward the information through ASPnet-
wp.exe(web process)
ASPnet-wp.exe file allocates memory which is called as ASP. net
work process where the execution of the request is done
The execution of the request will uses the compilers by identifying
the language used and generates the o/p by combining with user
interface
This complete process is done under CLR which sends back the
response to IIS
The communication b/n work process and web server uses pipelines
When the response is send back to the client by IIS the complete
information about the request and its process is removed from the
web server
The above point confirms that ASP. net is stateless technology
init
load
custom
prerender
unload

For every lifecycle execution of a web form .these events are fired
page_init event: used for initializing the component
Page_load used to load the web form
Custom event: the events which are fired by the controls of a web
form
ASP.net
56
Prerender:used to send the o/ p the client by combining user interface
and
the code
Unload: as the o/p is send it is called to remove the memory of the
web form

Objects in ASP. net:
Response
Request
Session
Application
Server
Cache
Trace
Ispostback etc..


Coding Techniques in ASP.net:

Coding techniques
Designing
code
Programming
code
.
A
S
P
x
Code inline model Code behind modell
Designing
code
Programming
code
.aspx
.aspx.cs





ASP.net
57

Webform programming models : to develop a webform in asp.net
we have two types of models
Code inline model
Code behind model
Code inline: defining user interface and business logic in a single file
with .aspx is called code inline model i.e. designing and programming
code are present in single file
It is used for migrating asp applications to asp.net
In real-time the designing of the webpage is done by the web designer
Limitations of code inline model:
Programmer need to wait until web designer completes designing so
programmers time will be wasted
There wont be any security for programming code from the designer
Maintenance of the code is difficult
Application development will take more time
No reusability of business logic
Code behind model: this method separates the user interface and
business logic in two files
1. User interface in .aspx file
2. Business logic in .cs or .vb file
It reduces the maintaince cost
increases the performance by reusability of the code
To develop a code file we should define a class inherited from
System.Web.UI.page Class
For web based applications there are two important namespaces in
asp.net
using System.Web.dll;
using System.Web.UI.dll;
Advantages of code behind:
Programmer need not wait for the designing
Security is maintained for the programming code from the designer
Application development will be completed at faster rate



ASP.net
58
Controls in asp. net
Controls
Client side server side
HTML HTML
server
Web server


Control: a control is a class which provides user interface which we
can access due and perform some actions.
Controls in asp. net are classified in to two types
1. Client side controls
2. Server side controls
Client side controls: the controls which are supported in ASP. net
due to backward compatibility and they are executed and stored on
client machine
All html controls are client side controls
Every HTML control will run at client side
They don't provide state management
They do not support object oriented programming
Server side controls: the controls which stores and executes on
server system are called as server side controls
ASP. net provides two types of server controls:
1. HTML SERVER CONTROLS
2. WEBSERVER CONTROLS


ASP.net
59

HTML SERVER CONTROLS: we can also make HTML controls to run
at server side by adding the attribute runat=server
Every HTML server control is a predefined class with some tag name
and control name

System.Web.UI.HtmlCont
rols.HTMlControl
Using
System.Web.UI.HtmlControls
Namespace 15
<Text area> HTML Textarea TextArea 14
<select> <option> HTMLSelect Select 13
<div> HtmlinputGenericcontrol Div 12
<hr> HtmlinputGenericcontrol Horizontal Ruler 11
<table>,<td>,<tr> HtmlTable
HtmlTableCell
HtmlTableRow
Table 10
<image> HtmlImage Image 9
<input type=Radio> HtmlinputRadioButton Input(Radio) 8
<inputtype=CheckBox> HtmlinputCheckBox Input(Check) 7
<input type=File> HtmlinputFile Input(file) 6
<inputtype=password> HtmlinputText Input(password) 5
<input type=Text> HtmlinputText Input(Text) 4
<input type=submit> HtmlinputButton Input(submit) 3
<input type=reset> HtmlinputButton Input(Reset) 2
<input type=button> HtmlinputButton Input(button) 1
Tag Class name Control name sno





ASP.net
60
All the HTML controls are inherited from System.Web.UI.Html.Htmlcontrol
names
System.Web.UI.HtmlControls.HTMlControl
HTML input control
HTML container control
HtmlInputButton
HtmlInputText
HtmlInputFile
HtmlInputCheckBox
HtmlinputradioButton
HtmlGenericControl
HtmlinputImage
HtmlinputTable
HtmlinputTableCell
HtmlinputTablerow
WEB SERVER CONTROLS or ASP. net CONTROLS:
All web server controls class name ,control name and tag name is
same
Every web server control should include under form tag
All ASP. net standard controls will run at server side only by default
every web server control includes run at=server attribute
All web server controls are converted into HTMl controls at the time of
generating the response
ASP.net-2008 has introduced some new techniques for simplifying
application designing by introducing master pages, themes and skins
All web server controls contains their own properties, events and
methods because all are inherited from a base class called
System.Web.UI.WebControls. WebControl
Every ASP. net standard control has a class like
Using System.Web.UI.WebControls.Textbox textbox
Using System.Web.UI.WebControls.Button button
Any ASP. net control we create within the webpage like Textbox 1,
ASP.net
61
Textbox 2, Button 1,Button 2 are objects to the respective classes
All asp. net controls will provide state management
All asp. net controls will support object oriented programming features
To create asp. net control we use the following syntax
<tag prefix: Class name id=any id runat=server>
<asp: Textbox id=TextBox1 runat=server>
For every asp. net standard control equivalent HTMl code is generated
on rendering
Difference between HTML controls and web server controls

Sno HTML CONTROLS ASP. net standard controls
1 all html controls run at
client side
Server side
2 Donot provide state
management
provide state management
3 Donot contain any class for
the control
Contains separate any class for
each control
4 Donot support oops support oops concepts
5 Can make to run at server
side by adding
runat=server
By default it is server side control

Common properties for all web server controls:
Back color: it is used to change the background color of a control
Border color: is used to change the border color of a control
Border style: is used to apply the style for the border like solid, double:
groove, inset, outset, dotted, dashed, none etc
Border width: is used to change the width of the control
Enabled: is used to activate or deactivate the control
Enable Theming (2.0): it is used to activate the theming for a control
Font: is used to apply font name, size and style
Forecolor: is used to apply the text color
Height: to apply the height of the control
Width: change the width of the control


ASP.net
62
Controls in ASP. net:
Different controls that are available in ASP.net are
Standard controls
Data controls
Validation controls
Navigation controls
Login controls
Web parts controls
Ajax extensions
General controls
Discussing each control with an example:


Label: is used to place some text on the web form as a heading or as a
caption for other control
Extra property: TEXT
Textbox: this control is used for accepting some text from the user and
is called as data entry control
Extra property: TEXT
TEXT MODE=single line, multiline, password
ROWS=SOME NO
COLUMNS=SOME NO
VALIDATIONGROUP=a validation group id
READONLY=TRUE, FALSE
MAXLENGTH=used to provide the limit some no
(Valid for single line and password)AUTOPOSTBACK=T/F
it is used to submit the page to the server automatically when the control
lost its focus










ASP.net
63

example with label and textbox :



Properties:

textbox1:autopostback=true

view source:

Protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Label3.Text = "hi" + TextBox1.Text;
}




Checkbox: this control is used to provide selection of more than one
options from the given group of options
properties: Autopostback--------->true, false
Checked.>true/false

Auto postback:when set to true page will be posted back to web server
whenever user activates the checkbox
When set to false page will not be posted back to web server when
user activates checkbox
Checked: stores true whenever checkbox is activated otherwise stores
false.
Default event of checkbox control is checked changed event
WELCOME TO ASP.NET
LABEL1
ENTER YOUR NAME
TEXTBOX1

LABEL2
LABEL3
ASP.net
64
Example for checkbox:
Enter ur name
Enter hobbies
dancing
playing
Browsing chatting
LABEL-3
SUBMIT

View source:

protected void cmdsubmit_Click(object sender, EventArgs e)
{
string s = txtsample.Text + "Hobbies are";
if (Chkdancing.Checked==true)
{
s = s + Chkdancing.Text + "";
}
if (Chkplaying.Checked == true)
{
s = s + Chkplaying.Text + "";
}
if (Chkbrowsing.Checked == true)
{
s = s + Chkbrowsing.Text + "";
}
if (Chkchatting.Checked == true)
{
s = s + Chkchatting.Text + "";
}
lbldisplay.Text = s;

}
ASP.net
65
example-2:





view source:
protected void Button1_Click(object sender, EventArgs e)
{
//REGISTER
int rent = 0; int acost = 0;
//verify room type selectede by user
if (R1.Checked)
//deluxe
rent = 1000;
else if (R2.Checked)
//ordinary
//verify amenities selected by user
if (C1.Checked)
acost = 3000;
if (C2.Checked)
acost = acost + 200;
//calculate the rent
rent = rent + acost;
Label4.Text ="registered <br> rent/day:"+rent;
}


Redirecting the user request to other webpage or the other
website
ASP.net
66
User request can be redirected to any webpage or to any website we
use two ways
Using design controls directly
By using the code



Using hyperlink: this control is used to redirect the user request to
any required webpage or website
Using hyperlink control we can create the link for both picture and text
Hyperlink control does not support command name and command
argument properties
Properties with hyperlink control:
Imageurl
Navigate url
Text
Image url: this property is used to set the path of image file that we
want to display in hyper link control
Navigate url:this property is used to set the url address path to which
we would like to Redirect the user request whenever user clicks on
hyper link button
Text:this property is used to set the display text to the user within the
hyperlink button
Go to toolbox drag hyperlink .>properties>text=click me--
navigate url=Default2.aspx

Redirecting user request
Using design
controls
Hyperlink
Link button
Using coding

Response. Redirect
Server. Transfer
ASP.net
67


Example:

Creating hyperlink for text:





To create link for image:
Search for gif,jpeg or icon file
Copy the required files and paste it in solution explorer of our website
Select the hyperlink------go to properties window------go to image
url property------
Click on ellipse button----------select the required image file------
click on ok
Run the application and check

ASP.net
68


LINK BUTTON CONTROL: this control is used to redirect the user
request to the required webpage or website
Using the link button control we can just create link to the only text
and cannot create link to the images
This control supports command name and command arguments
properties
Properties of link button:
Command arguments
Command name
Post back execution
Text
PostBackurl: this property is used to set the required address path
to which we would like to redirect the user request
Ex: select link button------go to properties window-----go to post
back url------click on elipse button--------select default.aspx------
click ---------ok
Run the application and check

ASP.net
69


Image Button: this control is used to redirect the user request to the
required webpage or website
Properties:
Command name
Command arguments
Image url
Image url:this property is used to set the path of the image using
which we want to create hyper link
Postback url:this property is used to set the url address path to
which we would like to redirect the user request when user clicks on
image button
Using image button control we can create the hyperlink only for
images not for text
This control will support both command name and command
arguments properties
Ex:select image button----properties----image url property----
click on elipse button-------------select the req image file---------
0k
Go to postback url-----------click on ellipse button and select
default.aspx
Run the app and check




ASP.net
70





Differences between Hyperlink link button and image button
























Hyperlink Link button Image Button
Link can
be created
to the text
and also
to the
image
Link can be created to
the text only and
cannot be created to
the image
Link can be created to the
image only and cannot be
created to the text
It doesnot
support
command
name an
command
arguments
properties
support command name
an command arguments
properties
support command name an
command arguments
properties
ASP.net
71




Redirecting the user request using coding
Response. Redirect(Default2.aspx);
Ex:
Server. Transfer(Default2.aspx);

Response.Redirect("Default2.aspx");
Server.Transfer("Default2.aspx");
Differences between Response.Redirect and Server.transfer

Server.transfer Response.Redirect
Used to redirect to any webpage in
any website present in the same
webserver
Used to redirect to any
webpage in any website
present in the same webserver
or in different webserver

Execution is fast Execution is slow
Cannot be user to pass any values to
the destination page
Can be user to pass any values
to the destination page


Button Controls:

ASP. net has provided three button controls for submitting
information to the server


BUTTONS
PUSH BUTTON LINK BUTTON
IMAGE BUTTON

ASP.net
72



THIS CONTROL IS USED TO PROVIDE EVENT-HANDLING FACILITY
OR TO EXECUTE THE REQUIRED CODE WHENEVER USER CLICKS ON
IT
Properties:
Command name
Command arguments
Post back url
Command name: this property is used to identify the control from which
event has been raised when same function or same event has been called
from button controls
Command arguments: this property is used to parse the required value
to the server whenever a user clicks on a button
Note: we can use the above properties only with command event of the
button control and we cannot use with click event
Post back url: this property is used to redirect the user request to any
webpage or website whenever user clicks on button
Events :an event is a member of a class which is used to perform some
kind of action or operation
The event will not be called every time rather at particular time period
only event will be called known as event firing or event raising

Eating
Drinking
singing
person
events

Whenever person gets hungry then only eating event will fire
Events associated with button controls:
Click event
Command event
Click event: this event will be fired when user clicks on the button
This event does not support command name and command argument
properties
Command event: this event is fired whenever user clicks on the
button
This event supports command name and command argument


ASP.net
73
Example with Click event:

textbox1
RED Green BLUE


View source:

protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.BackColor = System.Drawing.Color.Red;
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox1.BackColor = System.Drawing.Color.Green;
}
protected void Button3_Click(object sender, EventArgs e)
{
TextBox1.BackColor = System.Drawing.Color.Blue;
}










ASP.net
74
Example2 with click event:

Divide
cmdAdd cmdSubtract cmdMultiply
cmdDivide
Enter first no
Enter second no
txtResult
txtNum2
txtNum1
Result
subtract Multiply Add
Arithmetic problem.aspx




View source:

int a, b, c;
protected void Button1_Click(object sender, EventArgs e)
{
a= Convert.ToInt32(TextBox1.Text);
b= Convert.ToInt32(TextBox2.Text);
c=a+b;
TextBox3.Text=c.ToString();
}
protected void Button2_Click(object sender, EventArgs e)
{
a= Convert.ToInt32(TextBox1.Text);
b= Convert.ToInt32(TextBox2.Text);
c=a-b;
TextBox3.Text=c.ToString();
}

protected void Button3_Click(object sender, EventArgs e)
ASP.net
75
{
a= Convert.ToInt32(TextBox1.Text);
b= Convert.ToInt32(TextBox2.Text);
c=a*b;
TextBox3.Text=c.ToString();
}
protected void Button4_Click(object sender, EventArgs e)
{
a= Convert.ToInt32(TextBox1.Text);
b= Convert.ToInt32(TextBox2.Text);
c=a/b;
TextBox3.Text=c.ToString();
}
Example with command event:
Calling same function from two or more buttons
Select button1--properties--click on event---and type F1 and press
enter
Select button2--properties--click on event---and type F1 and press
enter
Enter any text
button1 button2









View source

Protected void F1(object sender, EventArgs e)
{
TextBox1.Text = "welcome";
}
Calling same function to perform the arithmetic operations when user cicks
on different buttons
1. Add the following command names to the buttons
ASP.net
76
cmdAdd ---------Add
cmdSubtract----subtract
cmdMultiply----Multiply
cmdDivide------Divide
2. Call the same function F1 from command event of all buttons
3. Write the following code




Divide
cmdAdd cmdSubtract cmdMultiply
cmdDivide
Enter first no
Enter second no
txtResult
txtNum2
txtNum1
Result
subtract Multiply Add
Arithmetic problem.aspx


View source: assignment


Listing Controls
This control will provide some list of items in a different appearance
from which we can select a single or multiple items
ASP. net 2.0 has introduced five types of listing controls
List Box:
Dropdown list:
Radio Button
Bulleted List
Common properties for first 3 list controls:
Auto post back=T/F
ASP.net
77
Data source Id=some collection
Data member=some collection
Datatextfield=column name
Items=some items
Events: selected index change
List Box: is used for selected single or multiple items by providing a
list of items.
Property: selection mode=single/multiple
Rows: some no
Dropdown list: used to display some collection of items in a
dropdown from which w can select any one
Checkbox List: it is a combination of checkbox and a List Box
it supports
multiple selection of items
Properties:
cell padding=some no
Cell spacing=some no
Repeat columns=some no
Repeat direction=horizontal/vertical
Repeat layout=table /flow
Text align=left/right
Radio Button List: supports only one item selection and is the
combination of radio button and list box
Properties are same as Checkbox List
Bulleted List Box: it is used to display information in bulleted format
or numbered format
Properties:
Bulleted style=numbered/lower arguments/upper arguments etc.
First Bulleted number=some no
Panel control: this property is used for grouping some control for
common alignment and applying some common properties
Page.IsPostback:this property is used for checking whether page is
loaded or reloaded
It returns false when the page is loaded for the first time otherwise
returns true.









ASP.net
78



ASP.net
79
Validation controls

Validation: it is a process of restricting the control by accepting the
proper input from the user i.e. it is a process of checking the values are
valid or not
Validations are of two types
Client side validations
Server side validations

s.no Client side validations Server side validations
1. Validating a webpage before
submitting the information is
called as client side validation
Validating a webpage on the server
after submitting the information is
called as server side validation
2. It can be perform using client
side script code return using
scripting languages
It can be perform using the code
placed on a server return by any
.net language
3. Provides faster response Provides slow response
4. Browser dependent Browser independent

If a webpage should validate properly and fastly then we have to use
client side and server side validations
But this process increases burden on the programmer to overcome this
problem MS. net has introduced 6 types of validation controls which
are inherited from System.web.UI.WebControls.BaseValidator


1. Required Field validator
2. Range Validator
3. Regular expression validator
4. Compare Validator
5. Customer Validator
6. Validation Summary----------------- displaying validation error
messages


ASP.net
80
common properties for all validation controls:
ControlToValidate =some control id
Error Message=some text
Text=some message
Display=static, dynamic none
Is Valid=T/F
Enabled Client Script=t/F
Set focus on error (2.0): t/f I is used to focusing the control when it
contains invalid value
ValidationGroup(2.0):some text or group ID

Required Field validator: used to check whether the the i/p control
contains value or not and if the value is not existing it provides error
message this control is used to check the emptiness of the control that
we are validating
If the control that we are validating doesnt contain any value then
required field validator will return false to the webpage
If the control that we are validating contains any value then required
field validator will return True to the webpage
Control to validate: this property is used to set the name of the control
that we are validating using req field validator
Error Message: this property is used to set the req message that is to
be displayed when req field validator returns false
Extra property: initial value=some text

Example




ASP.net
81
Properties:
Design: drag and drop required field validator
Properties of required field validator are
Control to Validate=TextBox1
Error Message=TextBox should contain some Text
Range validator: this control is used to check or validate user entered
data within the given range or not
Extra properties:
Maximum Value :this property is used to set the highest value with
which we would like to compare the user entered data
Minimum Value: this property is used to set the highest value with
which we would like to compare the user entered data
Type: this property is used to set the required datatype with which we
would like to compare the user entered data
Type=integer/string/double/date etc.

example





ASP.net
82
Properties:
Design: drag and drop range validator
Properties of range validator are
Control to Validate=TextBox2
Error Message=invalid age
Maximum value=25
Minimum Value=18
Type=integer
Compare validator: this control is used for comparing to controls or
used for comparing a control with the value
If both the controls contents are same then compare validator will
return true otherwise false
Properties:
control to compare: this property is used to set the control name
with which we want to compare the contents of the control that has
been set in control to validate property
Control to compare =some id
Value to compare=some value
Operator=equal, not equal,<,> etc
Type:string,Integer,double,Date etc.

Example








ASP.net
83
Properties:
Go to toolbox drag and drop compare validator
Control to validate=TextBox2
Control to compare =TextBox1
Operator=equal
Type: string,
Regular expression validation: this control is used to check or
validate whether user entered data is within the required format or not
like email id form or internet url address or phone no or in pin code
format no
If user entered data matches with the set format then reg expression
validator will return true to the webpage otherwise false
Properties:
Control to validate:
Error Message:



Properties:
Go to toolbox drag and drop Regular expression validator.
Validation expression=select internet url address

ASP.net
84
Validation Expression: this property is used to set the required
expression f format with which we want to compare
There are predefined expressions available to compare and also we
can write our own expressions
This control is used to perform the validations whenever existing
validation controls donot make the user requirements
This control is used to perform both client side and server side
validations
This is the only control in complete validation controls which is used to
perform both client side and server side validations
Properties
Control to validate
Client validation functions
Error message

Validation summary: it is used to display all the error messages in
that webpage This control is not used to perform any validations rather
it will display all other validation controls error messages as a group
together



User name Required fiels validator
password Required fiels validator
Retype password Compare validator
Age Range validator
Submit Validation summary

Example:
Drag and drop validation summary







ASP.net
85
Client validation functions: this property is used to set the required
java script function using we want to validate the required control data

Example using custom validator to perform client side validations
Example using custom validator to perform client side validations
Properties
Control to validate=textbox2.text
Error message=password should contain min of 6 characters
Client validation functions =F1
Enter username
Enter password Custom validator
submit

Go to source part of the html page and write the JavaScript function
code like
<head >
<script type="text/javascript">
function F1(X,Y)
{
if(Y.Value.length>=6)
{
Y.IsValid=true;
}
else
{
Y.IsValid=false;
}}
</script>
</head>
Button1_Click
ASP.net
86
{ Response.Redirect("page submitted");}

To perform client side validations using custom validator control
whatever the function we define the function should contain 2 args
always
1
st
arg will store the type of the control from which function has been
called
2
nd
arg contain 2 important properties
Value
IsValid
Value: property stores the data entered by user in the control that we
are validating
IsValid:this is a boolean property stores True/false and will return
either true or false to custom validator control when function execution
is completed
Example to perform server side validations using custom validator
control
In the above example we perform the validation to check password is
kanna or not
If user enters password > kanna then we display a message as
page submitted otherwise error message displayed

Enter username
Enter password Custom validator
submit





Properties
Control to validate=textbox2.text
Error message=password
Select custom validator ..> goto properties window..>click on events
button..>double click on server validate event write the following code
protected void Page_Load(object sender, EventArgs e)
{

}
ASP.net
87
protected void CustomValidator1_ServerValidate(object source,
ServerValidateEventArgs args)
{
if (args.Value == "kanna")
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid == true)
{
Response.Write("page is submitted");
}
}
Navigation controls: these controls are used for fast navigation between
the web page on a website
Some of the navigation controls are
MENU
TREE VIEW
SITEMAP PATH CONTROL
These controls are introduced only in 2.0 which we have to develop
using scripting languages or we have to download from Microsoft
control gallery in the previous versions of Asp. Net
MENU CONTROL:
Properties:
Disappear After=some millisecond
Items=Root, adding root, adding child, removing item
Items-----text, navigate url,image url,value
Dynamic menu style=some color
Example :

Step1: go to toolbox drag and drop menu control
Step2: select menu controls properties
Items=add root item----select new item---Text=HOME
similarly
Add ABOUTUS,CONTACT US
Step3: select HOME navigate url=home.aspx
select ABOUTUS navigate url=aboutus.aspx
select CONTACTUS navigate url=contactus.asp
ASP.net
88
step4:add home.aspx aboutus.aspx contactus.aspx to the existing
project



Step 5: Debug and check the output


TREE VIEW CONTROLS: This control is used for displaying some
information in a branched tree structure format with expansion and
collapsion
It always display in a vertical manner and does not support different
property for dynamic and static displaying
Properties:
Disappear After=some millisecond
Nodes=Root, adding root, adding child, removing item
Nodes--text, navigate url,image url,value
Dynamic menu style=some color
Example:
Step1: go to toolbox drag and drop treeview control
Step2: select menu controls properties
Nodes=add root item----select new item---Text=HOME
similarly
Add ABOUTUS,CONTACT US
Step3: select HOME navigate url=home.aspx
select ABOUTUS navigate url=aboutus.aspx
select CONTACTUS navigate url=contactus.asp
step4:add home.aspx aboutus.aspx contactus.aspx to the existing
project



ASP.net
89

Example:






SITE MAP PATH CONTROL: this control is used for providing the
navigation information information of a menu or a tree view control
It helps to navigate between the pages by providing navigation
information on the top or bottom of the web page
This control requires a sitemap file which is based on xml
We cannot directly work with sitemap path control to work with
sitemap we have to go either menu control or tree view control
Steps to work with sitemap path control
Step1: drag and drop menu control
Step2: go to website--- add new item- select sitemap---ok
Step3:then automatically website map is added
Step4: write the following code
<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-
Fil1.0">
<siteMapNode url="home.aspx" title="HOME"
description="WELCOME TO HOME PAGE">
<siteMapNode url="contactus.aspx" title="CONTACTUS"
description="WELCOME TO CONTACTUS PAGE" />
<siteMapNode url="" title="" description="" />
</siteMapNode>
</siteMap>
ASP.net
90




Step-5: select menu copntrol --properties---datasourceid=new
datasource---select sitemap---ok.
Step-6: debug and check the output










ASP.net
91




Calendar control example:



Steps to work with calendar control:
Properties visible=false
Step1: drag and drop calendar control
Step2: place link button and label
Step3: double click on link button and write the following code

LinkButton1_Click
{
//SHOW CALENDER
Calendar1.Visible = true;
}
Protected void Calendar1_SelectionChanged (object sender, EventArgs e)
{
TextBox1.Text = Calendar1.SelectedDate.ToShortDateString();
Calendar1.Visible = false;
ASP.net
92



ADO.net
Introduction to ADO.net
ADO. net:
Front end application: the application with which user interact like
forms, reports etc.
Front end tools :the software using which we design front end
application is known as front end tool
Ex for front end tool:
Dbase
FoxPro
MSAccess
Visual basic
Power Builder
D2K/oracle forms
.net
Java
Backend application: the application where originally user data is
stored
Back end tool: the software which we design back end application is
known as back end tool
Ex:Dbase,Msaccess,oracle,sybase,Foxpro,MSsqlserver,Mssql,MYSQL
I-layered approach: in this method both front end application and
backend application are designed using same tool and should be
presented only in single machine
Ex:Dbase,Foxpro,MSaccess


ASP.net
93

Disadvantages of I-layered approach:
Does not support centralized database
Cannot withstand large amount of data
I-layered approach


FE application
BE application


II-layered approach:


In this method both FE and BE application are designed using different
tools and can be present in different machines.
Both FE and BE tools will have only one set of native drivers and will
interact with third component known as middleware
Middle ware is designed in such a way that it can understand FE tool
native drivers
and any BE tool native driver


FE application
BE application


II-layered approach:
.
Disadvantages of II-layered approach:
ASP.net
94
As there are many front end tools and many back end tools
available in the market native drivers designed in any
Front tool for one back end tool cannot be used to interact
with other back end tool so every front end tool need to have one
Separate set of native drivers to interact with back end tool
II-layered approach:

In the same way every back end tool need to have one separate set of
native drivers for each front end tool
To overcome this disadvantage we use III-layered approach

III-layered approach

In this method both FE and BE application are designed using different
tools and can be present in different machines.
Both FE and BE tools will have only one set of native drivers and will
interact with third component known as middleware
Middle ware is designed in such a way that it can understand FE tool
native drivers and any BE tool native driver.

Ex:VB,power builder,
D2k/oracle forms
JAVA,. net
middleware
FE app
Native drivers
Native drivers
BE applications
Machine1/tool1
Machine2/tool2
DAO
RDO
ADO
ADO. net
Ex:MS ACCESS
MS SQLSERVER
ORACLE
MYSQL etc
Ex:OLEDB
ODBC
JDBC



ASP.net
95

ADO. Net

ADO. net is a native driver for .net technology designed by Microsoft
used to interact with database middleware.
It is one of the object model introduced from .net by MS
It is a common technology for all .net languages



FE application
Object model Driver
Database
DAO
RDO
ADO
ADO. net
ODBC
OLEDB
SQLCLIENT
ORACECLIENT


It provides managed database handling under .net environment it
enable us to communicate with any db by introducing different types
of providers
It has provided some set of class libraries for performing manipulation
on the database information using queries, procedures, functions etc.
It has introduced XML integration for universal data transformation
It has introduced a new concept called as data binding which provides
direct communication between data source and controls of the form

ASP.net
96
ADO versus ADO.NET (continued)
Feature ADO ADO.NET
XML
capabilities
XML aware XML is the native transfer
medium for the objects
Firewalls Firewalls block system-level
COM marshalling
XML flows through the firewall
via HTTP
Code Coupled to the language
used, various implementation
Managed code library Uses
Common Language Runtime,
therefore, language agnostic

ADO versus ADO.NET
Feature ADO ADO.NET
Primary Aim Client/server coupled Disconnected collection of
data from data server
Form of data in
memory
Uses RECORDSET object
(contains one table)
Uses DATASET object
(contains one or more
DATATABLE objects)
Disconnected
access
Uses CONNECTION object
and RECORDSET object with
OLEDB
Uses DATASETCOMMAND
object with OLEDB
Disconnected
access across
multi-tiers
Uses COM to marshal
RECORDSET
Transfers DATASET object via
XML. No data conversions
required

ASP.net
97
ADO.NET Architecture Diagram

ADO. net is an integral part of .net framework

ADO. net provides two types of programming
1. CONNECTION ORIENTED PROGRAMMING
2. DISCONNECTION ORIENTED PROGRAMMING
CONNECTION ORIENTED PROGRAMMING: in this method first we
establish the connection from the client to server and then perform the
required operations and close the connection again to perform any more
operations i.e.
Creating the connection
Opening the connection
Passing the query
Executing the query and
Closing the connection
In this programming once the connection is created it will be
maintained till the programmer explicitly closed it

ASP.net
98

client
server
1.Makes a connection
2.Pass some query and get result back
3.Disconnected from the database system
4.Makes the connection again
5.Pass some other query and get result back
6.Disconnected from the database system


2
nd
method:
In this method first we establish the connection to the database
Then send request for required data
And client requested data will be transferred to the network buffer at
server
And client will accessing data from the network buffer only


UI
db
N/W
buffer
N/W
buffer
UI
1
2
3
4
5
1
2
3
4
5
Client-1
Client-2
server

Step-1:connection is established to the server
Step-2:client sends the request for the required data
Step-3:client request is processed and result is transferred to the
separate memory allotted to the server for the client this memory is
known as network buffer
Step4:link will be created from network buffer to client
Step-5:client will be reading data from the network buffer





ASP.net
99
Data providers in ADO .net



Provider
name
Sqlclient Oracle
client
OLEDB ODBC
Namespace System.Data.
sqlclient
System.Data.
oracleclient

System.Data.Oledb

System.Da
ta.Oledb

Database
connection
Only
sqlserver
Only oracle Any database for
whicholedb drivers
are present
Any
database
for which
odbc
drivers are
present

Code
execution
Managed
code
Managed
code
Unmanaged code Unmanage
d code
Execution
speed
Faster Faster Slow Slow
Architectural
Complexity
Not complex Not complex Complex Most
complex
Others --------------- Namespace
is not
Available
directly
required to
add
reference
------------------ Included
from .net
framework
2.0 version







ASP.net
100
OBJECTS IN ADO. Net
sno Object name Class name
1. Connection SqlConnection
Oracle Connection
Oledb Connection
ODBC Connection
2. Command Sql Command
Oracle Command
Oledb Command
ODBC Command
3. Parameter Sql Parameter
Oracle Parameter
Oledb Parameter
ODBC Parameter
4. Transaction Sql Transaction
Oracle Transaction
Oledb Transaction
ODBC Transaction




sno Object name Class name
5. Data Reader Sql Data Reader
Oracle Data Reader
Oledb Data Reader
ODBC Data Reader
6. Data Adapter Sql Data adapter
Oracle Data adapter
ASP.net
101
Oledb Data adapter
ODBC Data adapter
7. Command Builder Sql Command Builder
Oracle Command Builder
Oledb Command Builder
ODBC Command Builder
8. Dataset Dataset
9. DataTable DataTable
10. Data Relation Data Relation
11. Data Row Data Row


1. Connection object: this object is used to establish connection to the
database
Using this object we cannot perform the transactions/operations on
the database objects like Tables, views, stored Procedures etc.
Properties with connection object:
Connection String
Connection Timeout
Database
Data source
State
Connection String: This property is used to set the parameters to
connect to required database based on the provider and database,
connection string is going to change
Connection Timeout: This is the time period in seconds that the front
end or ADO. net should wait to establish connection to the database
If connection to the database is not established within this time period
then time out error will be raised. Default timeout period is 15 seconds
ASP.net
102
Database : This property is used to set or get the database name that
connection object is to be used after establishing connection
This property is available only with sqlclient provider
Data source: This property is used to set or get the instance name of
the database server for which it is required to be connected
State: This is a Boolean property ,returns True if the connection to the
database is opened and live and returns false if the connection is to
the database is closed.

Methods with connection object:
Open( ) :This method is used to establish connection to the database
Close( ): This method is used to close an opened connection
Steps to work with connection object:
Step-1:include namespaces
Eg :using System. Data;
using System. Data.SqlClient;
Step-2: declare connection object
Syntax: Class name object name;
Ex: SqlConnection con;
Step-3: define connection object
syntax:objectname=new Classname(connectionstring);
Ex: con=new SqlConnection(connectionstring);
Step-4: open the connection
syntax: objectname.Open();
Ex: con.Open();
Step-5 close the connection
Ex: con.Close();

note: we can also use server name=. Or server name=local host if the
database is present on the same machine
Server name=IP address is given in real-time
IP address:127.0.0.1 i.e. IP address of local machine
Types of authentication modes in sqlserver:
Sqlserver supports two types of authentications
1. Sqlserver Authentication
2. Windows Authentication
Sqlserver Authentication :in this method we need to have separate
user id and password with sqlserver database then only we will be able
to connect to the sqlserver database
Windows Authentication: in this mode no need to have user id and
password by default it will take system authorized user



ASP.net
103


Example with connection object:

Sqlserver/sqlclient
Sqlserver/oledb
label1

View source:

using System.Data.SqlClient;
using System.Data.OleDb;
Button1_Click
{
//sqlserver authentication
SqlConnection con = new SqlConnection("user
id=sa;password=sa;database=model;data source=localhost");
//windows authentication
//SqlConnection con = new SqlConnection("initial
catalog=master;data source=localhost;integrated security=yes");
con.Open();
Label1.Text = "connected to sqlserver authentication";
con.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
//oledb connection
OleDbConnection con = new
OleDbConnection("provider=sqlOleDb;user
id=sa;password=sa;database=master");
con.Open();
Label1.Text = "connected to sqlserver with OLEDB";
con.Close(); }
2. Command object: this object is used to perform various operations on
database objects like tables,views,stored procedures etc
Command object will work with connection oriented object so first we
establish connection to database perform the required operation s and
close the connection to the database
Properties with command object:
Command Type: we will set command type value based on command
text
Command text : this property is used to set the required value
Command text can be
ASP.net
104
Sqlquery
Stored procedure name
Table name
If command text is sqlquery then command type is text
If command text is stored procedure then command type is stored
procedure
If command text is Table name then command type is table
Default value is text
Connection: this property is used to set the connection object name
using which we send the command object to the database server
parameters: This is collection property used to send required parameters
and their values with the database stored procedure
Steps to work with command object:
1. Declare command object
syntax:Classname object name;
Ex:sqlcommand cmd;
2. Define command object
syntax: object name=new Classname(command text,
connection object);
ex: cmd=new sqlcommand(Delete from Empdetails where
empid=117,con);
3. Mention command type:
Syntax: objectname.commandType=commandType.Value; //
Text(default),s.p,table
ex:cmd.CommandType=CommandType.Text
4. Execute command object
syntax: objectname.Executemethod();
ex:cmd.ExecuteNonQuery();

Differences between execute methods


s.no Execute Nonquery Execute Reader Execute scalar
1. It works with only
action queries
INSERT,UPDATE,DELET
E
It works with only non-
action queries
It works with only
non-action
queries that
include aggregate
function
2. Returns no of rows
affected by the query
Returns the total rows
data selected by the
query
Returns first row
and first column
value of the query
ASP.net
105





Example with command object to delete a record:


label1 DELETE







Step1: design the above screen

Step-2: go to database and create table

result
3. Return type is integer Return type is collection
of rows or table
Return type is
object
4. Return value is
optional and can be
assigned to an integer
variable
Return value is
compulsory and should
be assigned to another
object to another
known as Data Reader
Return value is
compulsory and
should be
assigned to a
variable of
required data
type
ASP.net
106


Create database
create database kanna
use created database
use kanna
create table
create table emp_detail(emp_no int primary key,emp_name
varchar(10),emp_designation varchar(10),emp_salary
varchar(10),emp_deptno int)
insert records into database
insert into emp_detail values(101,'kanna','PL','40000',20)
insert into emp_detail values(102,'sunil','PL','40000',20)
insert into emp_detail values(103,'murali','PL','40000',20)
insert into emp_detail values(104,'chakri','PL','40000',20)
insert into emp_detail values(105,'nagaraju','PL','40000',20)
insert into emp_detail values(106,'bobby','PL','40000',20)
selecting records
select * from emp_detail
Step-3: go to C# code window an write the following code


ASP.net
107
using System.Data.SqlClient
Button1_Click
{
SqlConnection con = new SqlConnection("user
id=sa;password=sa;database=kanna;data source=localhost");
con.Open();
SqlCommand cmd;
cmd = new SqlCommand("delete employee where
empid=102",con);
cmd.ExecuteNonQuery();
con.Close();
Label1.Text = i + "records deleted";
}

Example2:
Enter empid
label2 DELETE








ASP.net
108

View source:
using System.Data.SqlClient;
Button1_Click
{
SqlConnection con = new SqlConnection("user
id=sa;password=sa;database=kanna;data source=localhost");
con.Open( );
SqlCommand cmd;
cmd = new SqlCommand("Delete employee where
empid="+TextBox1.Text,con);
cmd.CommandType = CommandType.Text;
int i = cmd.ExecuteNonQuery( );
con.Close( );
Label2.Text = i + "records deleted";
}








ASP.net
109


Example3:
Insert, update and delete

Design:

Enter empid
Enter empname
Enter designation
Enter DOJ
Enter salary
Enter deptno
label7
insert Delete update




View source:

using System.Data.SqlClient;
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("user
id=sa;password=sa;database=kanna;data source=localhost");

SqlCommand cmd;
String s = "insert into emp_details values('" + TextBox1.Text + "','"
+ TextBox2.Text + "','" + TextBox3.Text + "',
'" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text +
"')";
ASP.net
110
cmd = new SqlCommand(s,con);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
Label7.Text = i + "records inserted"; }
protected void Button2_Click(object sender,EventArgs e)
{
SqlConnection con = new SqlConnection("user
id=sa;password=sa;database=kanna;data source=localhost");
SqlCommand cmd;
String s = "update emp_details set empname='" +
TextBox2.Text + "',designation='" + TextBox3.Text + "',
Doj='" + TextBox4.Text + "',salary='" + TextBox5.Text +
"',deptno='" + TextBox6.Text + "
where empid='" + TextBox1.Text + "'";
cmd = new SqlCommand(s, con);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
Label7.Text = i + "records updated"; }
Button3_Click {
SqlConnection con = new SqlConnection("user
id=sa;password=sa;database=kanna;data source=localhost");
SqlCommand cmd;
String s="delete emp_details where
empid='"+TextBox1.Text+"'";
cmd=new SqlCommand(s,con);
con.Open();
int i=cmd .ExecuteNonQuery();
con.Close();
Page.RegisterStartupScript("aa","<script> alert('record is
succesfully deleted')</script>");
}











ASP.net
111



DISADVANTAGES OF CONNECTION ORIENTED ARCHITECTURE:
1. When no of clients increase burden on the server will be increased and
performance will decrease
2. Though user is analyzing the data connection to the server is
maintained live this will waste the network resources

DISCONNECTED ARCHITECTURE:
In this method it is not required to establish prior connection to the
database whenever client sends request for any data connection will be
maintained automatically
UI
PA
UI
PA
db
3
1
2
4
1
2 3
4
Client-1 Client-2
Step
-1:client sends the request to the server for required data
Step-2:client request is processed and requested data is dumped into
client machines memory known as process area once the data is dumped
in to process area connection is no more maintained to the database
Step-3:user will be interacting with the data present in process area.
Step-4:after completion of the user interaction process area data will be
updated back to database at the time of updation connection is
automatically maintained








ASP.net
112



Second method:
client
application
C
O
N
N
E
C
T
I
O
N
data adapter
data adapter
dataset
db
respo
req
ADO. net
Db server
DISCONNECTED DATA CYCLE
Client-1
Application server


The programming where creating the connection, opening the
connection, passing the query, executing the query and closing the
connection is automatically done by
Data adapter.
the processed information is maintained under a temporary location
called as dataset
When the client gives the request to the application server the
application placed on that server gives the request to the database by
passing the query and creating the connection using data adapter class.
Data adapter class gets the resulted information and stored it in a
temporary location called as dataset
From the dataset application gets the information and generates the
response to sent back to the client
Once the response is sent dataset ,data adapter connection objects will
automaticallydestroyed.
ASP.net
113

Step-1:connection is established to the server
Step-2:client sends the request for the required data
Step-3:client request is processed and result is transferred to
the separate memory allotted to the server for the client this
memory is known as network buffer
Step4:link will be created from network buffer to client
Step-5:client will be reading data from the network buffer

When the client gives the request to the application server the
application placed on the server gives the request to the
database by passing the query and creating the connection using
data adapter class
Data adapter class gets the resulted information and store it in a
temporary location called as dataset
From the dataset application gets the information and generates
the response to sent back to the client
Once the response is sent dataset, data adapter connection
objects will automatically destroyed.
Dataset : it will work with disconnected architecture
Dataset is known as an in memory object
Dataset does not known how to interact with database
Dataset will use data adapter object to interact with database
Data adapter will use command object internally to get the data
from the database and to update the data back to database
Once data is fetched and stored in database connection to the
database is no more maintained and user will be no more
interacting with database data.
After user interaction again we can update dataset data back to
database
All the time updating database connection will be maintained
automatically.








ASP.net
114
dept
Empid Ename Designation Doj Salary Deptno
101 Kanna Projectlead 1/1/2007 40000 10
102 Sunil Teamlead 2/2/2007 30000 10
103 Murali Programmer 3/3/2007 20000 10
104 Chakri Developer 5/5/2007 10000 10
105 bobby DBA 1/1/2008 22000 30
Empdetails
Deptno Dname Location
10 Kanna Hyd
20 Sunil Banglore
30 Murali Delhi
40 Chakri Vizag
Dataset
0
1
0
1

ASP.net
115
1. Ds.Tables------------------- Empdetails
dept
Ds.Tables[0]
or
Ds .Tables [Empdetails ]
Ds.Tables[0]
Or Ds.Tables[Empdetails]
Ds.Tables[1]
Or Ds.Tables[Dept]
As dataset contains collection of tables each table is identified using index value or table
2. identification of rows
As every table contains collection of rows each row is identified using its index value
Ex:
Ds.Tables[0].Rows[1]
Empid Ename Designation Doj Salary Deptno
101 Kanna Projectlead 1/1/2007 40000 10
EmpDetails
Dept
EmpDetails
Dept
Identification of tables
Ds.Tables[1].Rows[1]
DNO
30
Dname
raju
location
delhi





ASP.net
116


3. Identification of columns: as every table contains collection each column is identified using index value or
column name
ex:Ds.Tables[0].columns[2]
4. identification of cell or a cell data: a cell is identified using matrix notation by using either rows collection
or columns collection
ex:Ds.Tables[0].columns[3][1]
or
Ds.Tables[0].columns[1][3]
Programmer
TL
SA
PL
DBA
Kumar


Steps to work with dataset
Declare data adapter object
syntax: Class name object name
ex: SqlDataAdapter da;
a. Declare dataset object
syntax: Class name object name
b. ex:Dataset ds;
c. Define data adapter object
d. syntax: objectname=new class name(select
command,connection object)
e. ex: da=new sqlDataAdapter(select * from
emp,con);
f. Define dataset object
g. syn: objectname=new class name();
h. ex: ds=new dataset();
i. Fill the data into dataset
j. syntax: Data adapterobject.fill(dataset
name,sometablename)
i.ex: da.Fill(ds,empdetails);

ASP.net
117


DATA BOUND CONTROLS:

These controls are used to display the database data to the user
Every data bound control will run at server side
For every data bound control equivalent html and java script
code is generated when rendered
Using data bound control we can
Display the data
Edit the data
Delete the data
Sort the data etc.
To work with any data bound control use the following three
steps
Designing the control
Preparing the data source
Attach the data source to data bound control
1. Designing the control: in this step we will design the control like
what columns are to be displayed what colors are to be given for
fore ground, back ground to provide editing ,deleting facilities or
not or sorting facilities or not etc.
2. Preparing data source :in this step we write the code to go to the
database get the data and fill in the dataset
3. Attaching the data source to data bound controls: in this step
whatever the data available in dataset will be attached to the
data bound controls so that user can view the data

Templates: these are used to provide designing facilities to the
data bound controls
We have various templates to provide designing facilities
Types of templates:
Header template
Item template
Separator template
Edit item template
Footer template
1. Header Template: this template is used to display the field
headings
this template is repeated only once within the data bound control
2. Item Template: This template is used to display original
records data within the data bound control. this template is
repeated for number of records present within the dataset table
ASP.net
118
3. Separator Template: this template s used to separate each
record with some line or symbol. this template is repeated for no
of records present in dataset table
4. Edit item template :this template is used to provide editing
facilities to any record present in the data bound controls
this template is repeated only once within the data bound
controls
5. Footer template: this template is used to display summary
information at the end or to display facility to add new record
using data bound controls.
This template is repeated only once within the data bound
controls
Edit Empid Ename Designation DOJ Salary Deptno
Edit 101 Sunil Programmer 1/1/07 8000 10
Edit 102 Kanna TL 2/1/07 20000 20
Update
cancel
103 Murali PM 3/3/07 30000 10
Edit 104 chakri testing 4/1/07 10000 20
Edit 105 Karee developer 6/1/07 8000 10
Add new
1
2
3
4
5

Common properties with all the data bound controls
1. Data source
2. Data member
Data source: This property is used to set the dataset as its data
source from which we want to display the data to the user
Data member: this property is used to set the table name of dataset
from which we want to display the data to the user
Common methods with all the data bound controls:
DataBind(); :- this method is used to bind the dataset table data
record by record and field by field to the data bound controls



ASP.net
119


Types of data bound controls:

1. Repeater control
2. Data list
3. Grid view
4. Forms view
5. Details view
Repeater control: this control is used to display the data in
plain text format to the user
Repeater control doesnt provide designing facilities
Repeater control doesnt provide editing facilities
Repeater control doesnt provide sorting facilities
Repeater control execution is faster as compared with data list
and grid view controls
Repeater controls is best to be used to display the data just in
plane format




Example :
Designing repeater control in table:







ASP.net
120
VIEW CODE:
STEP1: go to source and write the following code

<div>
<table>
<asp:Repeater ID="rpt1" runat="server">
<HeaderTemplate>
<tr><th>EMPID</th>
<th>EMP NAME</th>
<th>DESIGNATION</th>
<th>DOJ</th>
<th>SALARY</th>
<th>DEPTNO</th></tr>
</HeaderTemplate>
<ItemTempla <tr>
<td><%#DataBinder.Eval(Container.DataItem,"empid")
%></td>
<td><%#DataBinder.Eval(Container.DataItem,"empname")%
></td><td><%#DataBinder.Eval(Container.DataItem,"design
ation") %></td>
<td><%#DataBinder.Eval(Container.DataItem,"doj")
%></td>
<td><%#DataBinder.Eval(Container.DataItem,"salary")
%></td>
<td><%#DataBinder.Eval(Container.DataItem,"deptno")
%></td>
</tr>
</ItemTemplate>
</asp:Repeater>

</table>

</div>
Step-2: go to c# code window and write the following code
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
ASP.net
121

public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter da;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{ //step-2 prepare datasource
con = new SqlConnection("user
id=sa;password=sa;database=kanna;data source=localhost");
da = new SqlDataAdapter("select * from emp_details", con);
ds = new DataSet();
da.Fill(ds, "emp_details");
//step-3 attach database to databound control
rpt1.DataSource = ds;
rpt1.DataMember = "emp_details";
rpt1.DataBind();
}}

DATALIST
Data list control is similar to repeater control
Data list control provides very good designing facilities
It provides editing facilities
It provide adding new record facilities
We can also delete any record using data list control
It does not provide sorting facilities
It does not provides paging facilities
Execution of data list control is faster as compared with grid
view and slow as compared with repeater control
Properties with data list control:
Data Source
Data Member
EditItemIndex
Gridlines
Selected Index
Show Header
Show Footer

Data Source: this property is used to set the dataset as its
source from which we want to display the data in data list
control
Data Member :this property is used to set the table name of
the dataset from which we want to display the data within the
data list control
ASP.net
122
EdititemIndex: this property is used to set the data list control
in static mode or editable mode. If EdititemIndex is -1 then data
list control will be displayed in editable mode otherwise if
EdititemIndex is n then (n+1)th row is displayed in editable
mode .default value of EdititemIndex is -1
Gridlines: it is used to set whether gridlines are to be displayed
within the data list or not
Selected index: it is used to store index values of the row i.e.
selected by he user at runtime default value of selected index is
-1
Show Header : when set to true header template will be
displayed to the user
When set to false header template will not be displayed to the
user
Show Footer: when set to true Footer Template will be
displayed to the user
When set to false Footer Template will not be displayed to the
user
Events associated with data list control:
ItemCommand: this event will be fired when user selects any
selectable control within the data list
This event has a class known as Data List CommandEventArgs
class
This class has important properties like
1. CommandName
2. CommandArgument
3. Item
Item :this property stores the complete row from which item
command event is raised
Property with Item property:
ItemIndex:this property stores the index value of the row from
which item command event has been raised.
Method or function with item property:
FindControl(Controlname /Id) : This function is used to
search the required control within the row from which Item
Command event has been raised
This function also can be used along with data list control
Properties of data list control at runtime
Items: this property stores the complete list of rows present
within the data list
This is a collection property
Each rows can be identified using its index value
Data list examples: displaying the details in data list
control
ASP.net
123


Example1 with datalist control to display database data



Step1: go to source and write the following code
<div>
<asp:DataList ID="dl1" runat="server" GridLines="Both">
<HeaderTemplate>
EMPID EMP NAME DESIGNATION DOJ SALARY DEPTNO
</HeaderTemplate>
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem,"empid") %>
<%#DataBinder.Eval(Container.DataItem,"empname") %>
<%#DataBinder.Eval(Container.DataItem,"designation") %>
<%#DataBinder.Eval(Container.DataItem,"doj") %>
<%#DataBinder.Eval(Container.DataItem,"salary") %>
<%#DataBinder.Eval(Container.DataItem,"deptno") %>
</ItemTemplate>
</asp:DataList>

</div>

ASP.net
124

Step-2:go to C# code window and write the following code
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class datalist : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter da;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
//step-2 prepare datasource
con = new SqlConnection("user
id=sa;password=sa;database=kanna;data source=localhost");
da = new SqlDataAdapter("select * from emp_details", con);
ds = new DataSet();
da.Fill(ds, "emp_details");
//step-3 attach database to databound control
dl1.DataSource = ds;
dl1.DataMember = "emp_details";
dl1.DataBind();}}
ASP.net
125
example 2 to delete a record from database using datalist
contro with command arguments



Step-1:
Go to source and write the following code:
<div>
<asp:DataList ID="dl1" runat="server"
OnItemCommand="dl1_ItemCommand" GridLines="Both">
<HeaderTemplate>

EMPID EMP NAME DESIGNATION DOJ SALARY DEPTNO
</HeaderTemplate>
<ItemTemplate>
<asp:Button ID="b1" runat="server" Text="Delete"
CommandArgument='<%#DataBinder.Eval(Container.DataItem,"empid")
%>' />
<%#DataBinder.Eval(Container.DataItem,"empid") %>
<%#DataBinder.Eval(Container.DataItem,"empname") %>
<%#DataBinder.Eval(Container.DataItem,"designation") %>
<%#DataBinder.Eval(Container.DataItem,"doj") %>
<%#DataBinder.Eval(Container.DataItem,"salary") %>
<%#DataBinder.Eval(Container.DataItem,"deptno") %>
</ItemTemplate>
</asp:DataList></div>

ASP.net
126

Step-2 go to C# code window and write the following code:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class datalist2 : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter da;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
GetData();
}
}
private void GetData()
{
con = new SqlConnection("user
id=sa;password=sa;database=kanna;data source=localhost");
da = new SqlDataAdapter("select * from emp_details", con);
ds = new DataSet();
da.Fill(ds, "emp_details");
//step-3 attach database to databound control
dl1.DataSource = ds;
dl1.DataMember = "emp_details";
dl1.DataBind();


}


ASP.net
127
protected void dl1_ItemCommand(object source,
DataListCommandEventArgs e)
{
con = new SqlConnection("user
id=sa;password=sa;database=kanna;data source=localhost");
string s="delete emp_details where
empid="+e.CommandArgument.ToString();
SqlCommand cmd=new SqlCommand(s,con);
cmd.CommandType = CommandType.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GetData();
}}



Example 3 to delete a record from database using datalist contro
with out using command arguments

note: we can include any standard control within the data list
control by writing the code in item template or Header template
like
<ItemTemplate>
<asp:Button ID="b1" Text="Delete" runat ="server" />
</ItemTemplate>
Step1:designing

ASP.net
128



Step2: go to source and write the following code

<div>
<asp:DataList ID="DL3" runat="server"
OnItemCommand="DL3_ItemCommand">
<HeaderTemplate>
DELETE EMPID EMP NAME DESIGNATION DOJ SALARY DEPTNO
</HeaderTemplate>
<ItemTemplate>
<asp:Button ID="CMDDELETE" Text="Delete" runat="server" />
<asp:Label ID="lblempid" runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,"empid")%>'/>
<%#DataBinder.Eval(Container.DataItem,"empname") %>
<%#DataBinder.Eval(Container.DataItem,"designation") %>
<%#DataBinder.Eval(Container.DataItem,"doj") %>
<%#DataBinder.Eval(Container.DataItem,"salary") %>
<%#DataBinder.Eval(Container.DataItem,"deptno") %>
</ItemTemplate>
</asp:DataList>
</div>

ASP.net
129
Step-3:go to C# code window and write the following code
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class DATALIST3 : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter da;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
GetData();
}
}
private void GetData()
{
con = new SqlConnection("user
id=sa;password=sa;database=kanna;data source=localhost");
da = new SqlDataAdapter("select * from emp_details", con);
ds = new DataSet();
da.Fill(ds, "emp_details");
//step-3 attach database to databound control
DL3.DataSource = ds;
DL3.DataMember = "emp_details";
DL3.DataBind();
}
protected void DL3_ItemCommand(object source,
DataListCommandEventArgs e)
{
con = new SqlConnection("user
id=sa;password=sa;database=kanna;data source=localhost");
Label l1 = (Label)e.Item.FindControl("lblempid");
String s = "delete emp_details where empid=" + l1.Text;
ASP.net
130
SqlCommand cmd = new SqlCommand(s, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GetData();
}
}


Note:
to trap the row:datalist command event args class has a property known as item
property SO E.Item will store the respective row in which user clicks on delete button
i.e. if user clicks on 103 empid record delete button then e.Item will store
delete 103 Kanna TL 12/11/2009 40000 10
To trap the label:
We use a function known as Find Control with Item Property like
e.Item.FindControl(lblempid) ---103
Find control function will return any control with control datatype

ASP.net
131

Editing the data using data list control:
note: as long as EditItemIndex is -1 De set edit item data list data is displayed in static
mode
To display data list data in editable mode then set
DATLIST IN STATIC MODE
DATALIST IN EDITABLE MODE
EMPID ENAME DESIGNATION DOJ salary Deptno
101 Xxx Xxx Xxx Xxx Xxx
102 Xxx Xxx Xxx Xxx Xxx
103 Xxx Xxx Xxx Xxx Xxx
104 Xxx Xxx Xxx Xxx Xxx
105 Xxx Xxx Xxx Xxx xxx
EDIT/SAVE
EDIT
EDIT
EDIT
EDIT
EDIT


ASP.net
132


Example-4:
Editing with datalist control
Step-1: design



Step2: go to source and write the following code
<div>
<asp:DataList ID="DL4" runat="server"
OnItemCommand="DL4_ItemCommand">
<HeaderTemplate>
EMPID EMP NAME DESIGNATION DOJ SALARY DEPTNO
</HeaderTemplate>
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem,"empid") %>
<%#DataBinder.Eval(Container.DataItem,"empname") %>
<%#DataBinder.Eval(Container.DataItem,"designation") %>
<%#DataBinder.Eval(Container.DataItem,"doj") %>
<%#DataBinder.Eval(Container.DataItem,"salary") %>
<%#DataBinder.Eval(Container.DataItem,"deptno") %>
<asp:Button ID="cmdedit" runat="server" Text="edit"
CommandName="edit" />
ASP.net
133
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblempid" runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,"empid") %>' />
<asp:TextBox ID="txtename" runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,"empname")
%>'></asp:TextBox>
<asp:TextBox ID="txtdesignation" runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,"designation")
%>'></asp:TextBox>
<asp:TextBox ID="txtdoj" runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,"doj")
%>'></asp:TextBox>
<asp:TextBox ID="txtsalary" runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,"salary")
%>'></asp:TextBox>
<asp:TextBox ID="txtdeptno" runat="server"
Text='<%#DataBinder.Eval(Container.DataItem,"deptno")
%>'></asp:TextBox>
<asp:Button ID="cmdupdate" runat="server" Text="update"
CommandName="update" />
<asp:Button ID="cmdcancel" runat="server" Text="cancel"
CommandName="cancel" />
</EditItemTemplate>
</asp:DataList>
</div>
Step-3:go to C# code window and write the following code
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class datalist4 : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter da;
DataSet ds;
ASP.net
134
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
GetData();
}
}
private void GetData()
{
con = new SqlConnection("user
id=sa;password=sa;database=kanna;data source=localhost");
da = new SqlDataAdapter("select * from emp_details", con);
ds = new DataSet();
da.Fill(ds, "emp_details");
//step-3 attach database to databound control
DL4.DataSource=ds;
DL4.DataMember = "emp_details";
DL4.DataBind();
}

protected void DL4_ItemCommand(object source,
DataListCommandEventArgs e)
{
if(e.CommandName.ToString()=="edit")
{
DL4.EditItemIndex=e.Item.ItemIndex;
GetData();
}
else if(e.CommandName.ToString()=="cancel")
{
DL4.EditItemIndex=-1;
GetData();
}
else if(e.CommandName.ToString()=="update")
{

TextBox t1=(TextBox)e.Item.FindControl("txtename");
string mename=t1.Text;
t1=(TextBox)e.Item.FindControl("txtdesignation");
string mdesig=t1.Text;
t1=(TextBox)e.Item.FindControl("txtdoj");
string mdoj=t1.Text;
t1=(TextBox)e.Item.FindControl("txtsalary");
string msalary=t1.Text;
ASP.net
135
t1=(TextBox)e.Item.FindControl("txtdeptno");
string mdeptno=t1.Text;
Label l1 = (Label)e.Item.FindControl("lblempid");
con = new SqlConnection("user
id=sa;password=sa;database=kanna;data source=localhost");
string s="update emp_details set
empname='"+mename+"',designation='"+mdesig+"',doj='"+mdoj+"',
salary='"+msalary+"',deptno='"+mdeptno+"' where empid="+l1.Text;
SqlCommand cmd=new SqlCommand(s,con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
DL4.EditItemIndex=-1;
GetData();
}}
}




























ASP.net
136
GRIDVIEW CONTROL

Grid View control is used to display group of records to the user
Grid View control provides very good designing facilities
It provides editing facilities
It provide adding new record facilities
We can also delete any record using Grid View control
It provide sorting facilities
It provides paging facilities
Execution of Grid View control is slow as compared with data list
and repeater control
Properties with Grid View control:
Data Source
Data Member
EditIndex
Gridlines
Show Header
Show Footer
Allow Paging
Allow Sorting
Auto Generate Columns
Auto Generate Delete Button
Auto Generate Edit Button
Columns
Page Index
Pager Settings
Page Size
Data Source: this property is used to set the dataset as its source
from which we want to display the data in Grid View control
Data Member :this property is used to set the table name of the
dataset from which we want to display the data within the Grid View
control
EditIndex: this property is used to set the Grid View control in static
mode or editable mode. If EditIndex is -1 then Grid View control will
be displayed in static mode otherwise if EdititemIndex is n then
(n+1)th row is displayed in editable mode .default value of
EdititemIndex is -1
Gridlines: it is used to set whether gridlines are to be displayed within
the Grid View or not
Show Header: when set to true header template will be displayed to
the user, When set to false header template will not be displayed to
the user

ASP.net
137
Show Footer: when set to true Footer Template will be
displayed to the user
When set to false Footer Template will not be displayed to the
user
Allow Paging: when set to true data will be displayed in more
than one page.when false data will be displayed only in single
page
Allow Sorting: when set to true user can click on link button
that will be provided within the gridview.so that data can be
sorted on the required field.when false we cannot provide sorting
facilities to gridview
Auto Generate Columns: when set to true it is not required to
write code for templates to bind the data.when false it is
compulsory to write the data in templates to bind the data
Auto Generate Delete Button: when set to true a delete
button is created for each row automatically so that user can
click on delete button to delete any record .when false delete
button will not be generated for each row automatically
Auto Generate Edit Button: when set to true an edit button is
created for each row of the gridview control
Columns: this is a collection property which stores all the list of
columns that we display within the gridviewcontrol
Page Index: it is used to set the index value of the page that
we want to display to the user when Allow Paging is set to true
Pager Settings: it is used ti set the required settings to the
pager when allow paging is set top true
PageSize: it is used to set the no of records that we want to
display in each page when allow paging is set to true
















ASP.net
138
Events associated with Grid View control:

s.no EventName ClassName Properties Description
1. Page
IndexChanging
GridViewPageEven
tArgs
NewPageIndex Will be fired when
user clickson any
page no
2. Sorting GridViewSortEvent
Args
SortExpression Will be fired when
user clicks on any
column heading link
button created
automatically when
AllowSorting is true
3. RowDeleting GridView
DeleteEventArgs
RowIndex Will be fired when
user clicks on delete
button created
automatically
AutoGenerate
Delete Button is
true
4. RowEditing GridView Edit
EventArgs
NewEditIndex Will be fired when
user clicks on Edit
button created
automatically when
AutoGenerate Edit
Button is set to true
5. RowUpdating GridviewUpdate
EventArgs
RowIndex It will be fired when
user clicks on
update button
created
automatically when
AutoGenerate Edit
Button is set to true
6. RowCancellingE
dit
GridviewCancelEdi
tEventArgs
RowIndex It will be fired when
user clicks on cancel
button created
automatically when
AutoGenerate Edit
Button is set to true






ASP.net
139
Displaying data in Grid view controls




<div>
<asp:GridView ID="gv1" runat="server" Height="337px">
<Columns>
<asp:BoundField HeaderText="EMPID" DataField="empid" />
<asp:BoundField HeaderText="EMPNAME" DataField="empname"
/>
<asp:BoundField HeaderText="EMPDESIGNATION"
DataField="designation" />
<asp:BoundField HeaderText="EMPDOJ" DataField="doj" />
<asp:BoundField HeaderText="EMPSALARY" DataField="salary" />
<asp:BoundField HeaderText="EMPDEPTNO" DataField="deptno" />
</Columns>
</asp:GridView>
</div>





ASP.net
140
using System.Data.SqlClient;
public partial class gridview1 : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter da;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
GetData();
}
}
private void GetData()
{
con = new SqlConnection("user
id=sa;password=sa;database=kanna;data source=localhost");
da = new SqlDataAdapter("select * from emp_details", con);
ds = new DataSet();
da.Fill(ds, "emp_details");
//step-3 attach database to databound control
gv1.DataSource = ds;
gv1.DataMember = "emp_details";
gv1.DataBind();
}
}


















ASP.net
141



Paging with grid view:



<div>
<asp:GridView ID="GridView1" runat="server"
AllowPaging="True"
OnPageIndexChanging="GridView1_PageIndexChanging" >
</asp:GridView>

using System.Data.SqlClient;
public partial class gridview2 : System.Web.UI.Page
{

SqlConnection con;
SqlDataAdapter da;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
ASP.net
142
GetData();
}
}
private void GetData()
{
con = new SqlConnection("user
id=sa;password=sa;database=kanna;data source=localhost");
da = new SqlDataAdapter("select * from emp_details", con);
ds = new DataSet();
da.Fill(ds, "emp_details");
//step-3 attach database to databound control
GridView1.DataSource = ds;
GridView1.DataMember = "emp_details";
GridView1.DataBind();
}

protected void GridView1_PageIndexChanging(object sender,
GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GetData();
}
}





















ASP.net
143
Checkboxes with gridview:



<div>
<asp:GridView ID="GridView1" runat="server"
BackColor="White" BorderColor="#3366CC"
BorderStyle="None" BorderWidth="1px" CellPadding="4"
Height="194px" Style="z-index: 100;
left: 316px; position: absolute; top: 71px" Width="444px"
AutoGenerateColumns="False">
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True"
ForeColor="#CCFF99" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399"
HorizontalAlign="Left" />
<HeaderStyle BackColor="#003399" Font-Bold="True"
ForeColor="#CCCCFF" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%-- <asp:RadioButton ID="r1" runat="server" />--%>
<asp:CheckBox ID="c1" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="productid"
DataField="productid" />
ASP.net
144
<asp:BoundField HeaderText="productname"
DataField="prname" />
<asp:BoundField HeaderText="cost" DataField="cost" />
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" BackColor="Gray"
OnClick="Button1_Click"
Style="z-index: 101; left: 481px; position: absolute; top:
321px" Text="TOTAL"
Width="100px" />
<asp:Label ID="Label1" runat="server" BackColor="Lavender"
Font-Bold="True" ForeColor="Maroon"
Style="z-index: 103; left: 328px; position: absolute; top:
387px" Text="Label"
Visible="False" Width="431px"></asp:Label>

</div>

using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
SqlConnection con = new SqlConnection("user
id=sa;password=sa;database=gridview");
SqlDataAdapter da = new SqlDataAdapter("select * from
product", con);
DataSet ds = new DataSet();
da.Fill(ds, "product");
GridView1.DataSource = ds.Tables["product"];
GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string s="";
int tot = 0;

foreach(GridViewRow r in GridView1.Rows)
{
CheckBox c = (CheckBox )r.FindControl("c1");
if (c.Checked!=false)
ASP.net
145
{
s = s + r.Cells[2].Text + "<br>";
tot = tot + int.Parse(r.Cells[3].Text);

}
}
Label1.Visible = true;
Label1.Text = "products sale:<br>" + s + "total:" + tot;
}

}



Display radio buttons in grid view:










ASP.net
146
Step-1:

<div>
<asp:GridView ID="GridView1" runat="server" BackColor="White"
BorderColor="#3366CC"
BorderStyle="None" BorderWidth="1px" CellPadding="4"
Height="194px" Style="z-index: 100;
left: 322px; position: absolute; top: 82px" Width="444px"
AutoGenerateColumns="False">
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True"
ForeColor="#CCFF99" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399"
HorizontalAlign="Left" />
<HeaderStyle BackColor="#003399" Font-Bold="True"
ForeColor="#CCCCFF" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:RadioButton ID="r1" runat="server" GroupName="g1"/>

</ItemTemplate>
</asp:TemplateField>
<%--<asp:TemplateField>
<ItemTemplate>
<asp:Image runat="server" ID="im1" ImageUrl='<%
#Server.MapPath("images\\")+DataBinder.Eval(Container,"dataitem.pi
mage") %>' Width="75" Height="75" />
</ItemTemplate>
</asp:TemplateField> --%>
<asp:BoundField HeaderText="productid"
DataField="productid" />
<asp:BoundField HeaderText="productname"
DataField="prname" />
<asp:BoundField HeaderText="cost" DataField="cost"
/>
<asp:ImageField HeaderText ="product Image"
DataImageUrlField="pimage" ControlStyle-Height="60" ControlStyle-
Width="60"></asp:ImageField>


</Columns>
</asp:GridView>
ASP.net
147
<asp:Button ID="Button1" runat="server"
OnClick="Button1_Click" Style="z-index: 103;
left: 898px; position: absolute; top: 167px" Text="Click"
Width="109px" />
&nbsp;&nbsp;
<asp:Label ID="Label1" runat="server" BackColor="Lavender"
Font-Bold="True" ForeColor="Maroon"
Style="z-index: 102; left: 340px; position: absolute; top:
9px" Text="Label"
Visible="False" Width="431px"></asp:Label>
&nbsp;</div>

Step-2

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

if (IsPostBack == false)
{
SqlConnection con = new SqlConnection("user
id=sa;password=sa;database=gridview");
SqlDataAdapter da = new SqlDataAdapter("select * from
product", con);
DataSet ds = new DataSet();
da.Fill(ds, "product");
GridView1.DataSource = ds.Tables["product"];
GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
ASP.net
148

foreach (GridViewRow r in GridView1.Rows)
{
RadioButton R = (RadioButton)r.FindControl("r1");
if (R.Checked )
{
Label1.Visible = true;
Label1.Text = "products ID:" + r.Cells[1].Text + " <br>
Name:" + r.Cells[2].Text + "<br> Cost is: " + r.Cells[3].Text + "";

R.Checked = false;

}
}

}




























ASP.net
149
ADROTATOR CONTROL

It will rotate different functions to different clients
This requires two steps
1. preparing advertisement files
2. providing advertisement file file to adrotator
Structure of advertisement file::
In asp 3.0 advertisement file is text file in asp.net it is xml file this
provides more flexibility compares to text file
<Advertisements>
<Ad>
<imageurl>ad image file</imagefile>
<NavigateUrl>ad info page</NavigateUrl>
<Alternate Text>..<Alternate Text>
<Height>.</Height>
<Width>.</Width>
<impressions></impressions>
<description></description>
</Ad>
</Advertisements>
Xml is case sensitive the tag name is casesensitive
imageUrl:it will represent advertisement file
<NavigateUrl> it will represent advertisement info page
<Alternate Text> it will represent tooltip text for ad or it will be
displayed when image is not downloaded
<impressions> it will specify priority for advertisement the add with
more impressions will be given to more no of clients
The add with more impressions will be given to more no of clients

Example:
Step-1: create website-- add existing item-- add three image

Step 2: add advertisement webpage files
Website-- add new item-- html page- name=pocketpc.html-
--.add and write the following code
<!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>
<title>Untitled Page</title>
</head>
<body>
POCKET PC INFO PAGE
</body>
ASP.net
150
</html>
Similarly add handycom.html and speakers.html

Step-3: place advertisement file into website
Website menu--add new item--XMLFile.xml---add. And write the
following code
<?xml version="1.0" encoding="utf-8" ?>
<Advertisements>
<Ad>
<ImageUrl>ASP.jpg</ImageUrl>
<NavigateUrl>pocketpc.html</NavigateUrl>
<AlternateText>pocketpcinfo</AlternateText>
<Impressions>5</Impressions>
<Heigth>150</Heigth>
<Width>150</Width>
<description>latest arrival ofg pocket pc</description>

</Ad>
<Ad>
<ImageUrl>KANNAASP.jpg</ImageUrl>
<NavigateUrl>speakers.html</NavigateUrl>
<AlternateText>speakersinfo</AlternateText>
<Impressions>5</Impressions>
<Heigth>150</Heigth>
<Width>150</Width>
<description>speakers at lowestcots grab offer</description>

</Ad>
<Ad>
<ImageUrl>KANNAASPWITHFAQS.jpg</ImageUrl>
<NavigateUrl>handycom.html</NavigateUrl>
<AlternateText>handycoms info</AlternateText>
<Impressions>2</Impressions>
<Heigth>150</Heigth>
<Width>150</Width>
<description></description>

</Ad>

</Advertisements>




ASP.net
151
Step-4:
Go to default.aspx and design



Step-5:properties of Adrotator adrotator will call adcreated
subprogram after advertisement is created this subprogram
will provide complete advertisement info.
In this subprogram read description of advertisement and place
into label
Double click on adrotator and write the following code
protected void AdRotator1_AdCreated(object sender,
AdCreatedEventArgs e)
{
Label1.Text = e.AdProperties["description"].ToString();
}










ASP.net
152
Step-6 : press f5 and check the output

























ASP.net
153
CSS in ASP. net

It is the unique concept of DHTML which is used for applying
formatting styles on the existing tags or controls
To work with CSS in ASP. net we have special type of flow
To create a style definition file
Take a ASP. Net website----website menu----add new item--
-select style sheet----name=style sheet. Css ------ok
body
{
background-color:Blue;


}
.myStyle
{
font-size:xx-large;
color:Red;
}
To apply this style sheet take a asp. net webpage i.e. .aspx page
Go to html window place the cursor in the head tag-----go to
solution explorer
---drag and drop style sheet file in the head tag
This tag automatically adds a link tag in the HTML code window
To apply the class as a selector on the control i.e. my style block
definition
Add a button control on the form-------.properties of button ---
cssclass=myStyle
DRAWBACKS OF CSS:
CSS is browser dependent
It applies the styles on the client machine
It is not supportable by the ASP .net control properties
To overcome this problems of CSS ASP .net 2.0 has introduced a
new concept called
THEMES
SKINS
MASTER PAGES







ASP.net
154
THEMES AND SKINS

Theme is a concept which applies common formatting style for
the controls on a website web pages
To apply themes we have to generate skin file
SKINS: it contains the code for formatting the controls
To apply skin file as a theme we have three ways
1. Using page directive
2. Using web.config file
3. Using the code window
Using page directive : go to html code window of a web page in
the page directive
<%@ Page Language="C#" AutoEventWireup="true" Theme=folder
name" > where skin file is maintained
Using web.config file: go to web.config file
<system.web>
<pages theme="SkinFile\"></pages>
</system.web>

Example with THEMES AND SKINS:

STEP-1: Open devenv---default.aspx--and design the following
webpage






ASP.net
155
Step-2: go to website--- add new item--- and design
default2.aspx as



Step-3: go to website- add new item-- select skinfile-- add-
yes-- automatically App_Themes\SkinFile\SkinFile.skin will
be added-- delete the code available in the skinfile-- and
write the following code
<asp:TextBox runat="server" BackColor="Blue"
BorderColor="Aqua"></asp:TextBox>
<asp:Label runat="server" BackColor="green"
BorderColor="yellow"></asp:Label>

Step-4: go to Default.aspx and write the following code

<%@ Page Language="C#" AutoEventWireup="true"
Theme="SkinFile" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
Similarly go to Default2.aspx and write the following code


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

ASP.net
156
Step-5: execute default.aspx and Default2.aspx and check the output
the skin file is applied to every page

o/p:







ASP.net
157


MASTER PAGES:

Master pages are used to provide a practical solutions for page
templating .this is anewconcept introduced from ASP.net-2005
.it is used to maintain the part of the webpage as constant
through out the website.

Example:

Step-1:
Start- run-- devenv-- create website--- add new item--
Select master page template-- add

Step-2: cut the content place holder -- go to layout-- insert
table-- select template- select header ,footer and side
template









ASP.net
158

Step-3: paste the content place holder in C




Step4: place some image in A
Step-5: drag and drop a tree view control in B



Step-6: execute the default page and execute.
ASP.net
159
MASTERPAGES AND THEMES
AND SKINS AND NAVIGATION
CONTROLS
STEP-1: GOTO-- START----- RUN----- DEVENV---- OK
STEP-2:

STEP-3:

STEP-4: GO TO DESIGN WINDOW AND GOTO---- WEBSITE --- ADD NEW
ITEM---- SELECT MASTERPAGE TEMPLATE----
NAME=MASTERPAGE.MASTER-------- ADD.
ASP.net
160


STEP-5: GO TO SOURCE CODE AND CUT THE CONTENT PLACEHOLDER
AND GO TO DESIGN WINDOW AND DRAG AND DROP HTML TABLE
ASP.net
161


STEP-6:FOR BETTER UNDERSTAND I HAVE NAMED EACH AND EVERY
ROW DONT CONSIDER THE NAMES IN MASTERPAGE JUST FOR YOUR
UNDERSTANDING ONLY I HAVE GIVEN.




PLACE MENU CONTROL IN A SELECT ELIPSE BUTTON IN MENU CONTROL
AND CLICK ON AUTOFORMAT SELECT ONE STYLE.
PASTE CONTENT PLACEHOLDER IN E
PLACE IMAGE CONTROL IN B NAME=IMAGE1
PLACE IMAGE CONTROL IN C NAME=IMAGE2
TO PLACE IMAGES IN IMAGE CONTROL1 AND IMAGE CONTROL2 GOTO
SOLUTION EXPLORER RIGHT CLICK ON PATH
NEWFOLDER---- RENAME=IMAGES--- RIGHTCLICK ON IMAGES--- ADD
EXISTING ITEM--- SELECT SOME IMAGES--
SELECT IMAGE1-- IMAGEURL=SOMEIMAGE
SELECT IMAGE2-- IMAGEURL=SOMEIMAGE
ADJUST THE SIZE.




ASP.net
162



STEP-7: SELECT MENU CONTROL------ GOTO PROPERTIES------
MAKE ORIENTATION =HORIZONTAL BY DEFAULT IT IS VERTICAL
ASP.net
163
ITEMS=SELECT ROOT ITEM---- TEXT=HOME SIMILARLY ADD
ABOUTUS, CONTACTUS, JOBSEEKER AND JOBPROVIDER SELECT
JOBSEEKER AND ADD CHILD ITEM TEXT=LOGIN JOBSEEKER
SIMILARLY SELECT JOB PROVIDER AND ADD CHILD ITEM TEXT=LOGIN
JOB PROVIDER


STEP-8: GO TO WEBSITE ADD NEW ITEM----- SELECT WEBFORM----
NAME=HOME.aspx-- SELECT MASTERPAGE CHECKBOX---- ADD
SIMILARLY ADD CONTACTUS.aspx, ABOUTUS.aspx,
JOBSEEKERLOGIN.aspx PAGES

ASP.net
164

MASTERPAGE LOOKS LIKE


STEP-9: GO TO HOME.ASPX AND DRAG AND DROP SOME IMAGE IN
CONTENT PLACEHOLDER
ASP.net
165
NOTE: WE CANNOT EXECUTE MASTERPAGE MASTERPAGE IS ONLY
USED TO IMPORT INTO ANY OF THE ASPX PAGES
NOW GO TO WEBSITE IN HOME.aspx PAGE AND SELECT SET AS
STARTPAGE
PRESS F5 AND CHECK THE OUTPUT
STEP-10: SIMILARLY ADD SOME DATA IN CONTENT PLACEHOLDER IN
ABOUTUS.aspx AND CONTACTUS.aspx PAGES
STEP-11: GO TO JOBSEEKERLOGIN.aspx DESIGN





STEP-12: GO TO REGISTERATION.aspx AND DESIGN
ASP.net
166








STEP-13:
THEMES AND SKINS IN ASP.NET
I WANT TO MAINTAIN LABELS AND TEXTBOXES STYLE CONSTANT
THROUGHOUT THE WEBSITE.
GO TO WEBSITE ------ ADD NEW ITEM------ SELECT SKINFILE--------
EXTENSION=SKINFILE.SKIN
ASP.net
167

CLICK YES

SOME GREEN COLOR DEFAULT CODE WILL BE COMING DELETE THE
CODE IN APP_THEMES/SKINFILE/SKINFILE.SKIN
ASP.net
168

ADD THE FOLLOWING CODE:
<asp:Label runat="server"
BackColor="Honeydew"
BorderStyle="Groove" Font-
Size="Large" Font-Bold="true">
</asp:Label>
<asp:TextBox runat="server"
BackColor="Green" ForeColor="Red"
BorderStyle="Groove" Font-
Size="Large" Font-Bold="true">
</asp:TextBox>

GO TO JOBSEEKERLOGIN .aspx
ASP.net
169
<%@ Page Language="C#" Theme="SkinFile"
MasterPageFile="~/MasterPage.master"
AutoEventWireup="true"
CodeFile="JOBSEEKERLOGIN.aspx.cs"
Inherits="JOBSEEKERLOGIN" Title="Untitled Page" %>
Similarly goto REGISTER.aspx AND WRITE THE
FOLLOWING CODE
<%@ Page Language="C#" Theme="SkinFile"
AutoEventWireup="true" CodeFile="REGISTER.aspx.cs"
Inherits="REGISTER" %>
SIMILARLY WHERE EVER YOU WANT TO APPLY THE
THEME YOU HAVE TO WRITE THE SAME CODE
PRESS F5 AND CHECK THE OUTPUT


STATEMANAGEMENT IN ASP. Net
It is the process of maintaining some information between
multiple requests and responses
It is also defined as an art of retaining values between multiple
web pages
As Asp .net is a stateless technology where with every request
a page object is created on the server and with every response
the object is destroyed on the server
If we consider a website like online shopping where user can
select multiple items to buy with each request the object is
created then all the items details may not maintain to generate a
bill.becoz of ASP. net stateless nature. in this criteria we need to
maintain the information about the selected items in a
temporary memory either on the client or on the server
machine to perform this operation ASP .net has introduced state
management
state management is ASP .net contains 6 types
1. View state
2. URL encoding
3. Cookies
4. Sessions
5. Application
6. Caching
ASP.net
170

1. View state: it is one of the state management concept which is
used for maintaining the state of a control in around trip fashion
i.e. submitting the data to the server and getting the response
back to the client
It maintain the information on the server under a collection class
called as System.Web.UI.StateBagClass and on the client
machine it is maintained in terms of a hidden field with a name
view state
<input type=hidden field name=-viewstste id=-view state
value=---- />

The value which is maintained in view state is in a base 64
format which is easy to read a hexa decimal value
Any hacker can perform reverse engineering to the base 64
value and can get the actual value from it
To provide security for our view state data
ASP .net has provided two ways
1. Using EnableViewStateMacAttribute
2. Using Encrypting the data
Using EnableViewStateMacAttribute :This attribute
generates strong check sum value which is a crypto graphical
hash code
When the page is submitted to the server this checksum is
maintained on the client and is compared with the response
value if both matches accept the page otherwise rejects the page
Html code window:
<%@ Page Language="C# ..
EnableViewStateMac="true" %>
Note: but this check sum is readable and modifiable to overcome
this problem
We should encrypt the data
Using encrypting the data : to secure the view state
information from changing its value we should apply strong
encryption standards i. e
3DES--triple digital encryption standards this encryption
format has to mention in a configuration file
Go to web.config file
<system.web>
<machineKey validation="3DES"/>
</system.web>
Note: view state information should be encrypted only
1. For the web pages which contains valuable information otherwise
it may slow down our process
ASP.net
171
2. Every control in ASP .net contains Enable View State property
due to which the view state maintains the information about the
control
IIQ :if this property is false then also view state maintains the
information about the control because for a website it is a
default setting
Custom view state: to develop our own view state information
.net has provided a new object called as view state object under
a page class
To store information in view state
Syn: Viewstate[-----]=some value;
To get the information from view state
Syn: variable =Viewstate[------];
To perform serialization and deserialization for a specific object
using view state
Go to--website menu----add new item----select class
template--name=class1.csok
A dialogue box will be displayed which ask the file to be stored in
app-code folder-yes
[Serializable]
public class employee
{
int eno;
String ename;
public employee(int no, String en)
{
eno = no;
ename = en;
}
public int Empno
{
get
{
return eno;
} }
public String Empname
{
get
{
return ename;
} }}


ASP.net
172

Drawback of view state:
1. The life span of a view state is till the page is executed within a
post back execution
2. Once the page is submitted to some other page or redirected to
some other page view state is automatically destroyed under
server.
URL ENCODING: it is a process of transferring information from
one web page to another web page by concading some
parameters along with it
Response. Redirect :it is used for navigating our execution from
one web page to another web page
Response.Redirect("f1.aspx? a=10");
Response.Redirect("f1.aspx? a=10 & b=aaa &c=true");
? Is used for separating the path parameter list
& is used for separating the parameter list.
Request.Querystring:it is used for accepting the value from a
url specified under Response. Redirect
Server. Transfer: this method is used for transferring the
execution from one web page to another web page by
terminating the execution of first page
Request.Params: it is used for accepting the information from
previous controls and also retrieves the information from a url
Design :






protected void Button1_Click(object sender, EventArgs e)
{
employee e1 = new employee(10, "kanna");
ViewState["emp"] = e1;
Label1.Text = "employee object is serialized";
}
protected void Button2_Click(object sender, EventArgs e)
{
employee e1 = (employee)ViewState["emp"];
Label1.Text = "Empno is:" + e1.Empno + "<br>";
Label1.Text = "Empname is:" + e1.Empname;
}
store
label1
ASP.net
173


Design





Drawbacks of url encoding:
1. Can transfer information only to the next page
2. The data is visible in the url so no security for the data
3. Only limited bytes of information can be passed 1024 bytes of
information










Item1
Item2
Item3
Item4
item5
This is check box
submit
Button1_Click
{
String lb = ListBox1.SelectedItem.Text;
bool cb = CheckBox1.Checked;
//Response.Redirect("urlencodeing2.aspx?
L="+lb+"&C="+cb+);
Server.Transfer("urlencodeing2.aspx");
}
Go to website-- add new item-- urlencoding2.aspx:
Page_Load
{
// String lb = Request.QueryString["L"];
// String cb = Request.QueryString["C"];
String lb = Request.Params["ListBox1"];
label
ASP.net
174
COOKIES

Cookie is the information which is stored on the client machine.
It is accessible by a particular user for n number of web pages of
a website
Cookies are classified in two types






cookies
in memory Out memory
Single value multi value Multi value Single value
ASP.net
175

When the client gives the request cookie is created on the server
but it is stored on the client by sending along with the response
and for the next request and the response cookie is taken to the
server and the client
Single value in memory cookie: a cookie which holds only one
value with one name is called as single value in memory cookie.
syn for creating cookie: to create or to retrieve information
from a cookie asp. net has provided Http Cookie class
syn 1:HttpCookie object=new
HttpCookie(cookiename,cookievalue);
Response.Cookies.Add(object);//to store the cookies on client
machine
syn2:HttpCookie object=new HttpCookie(cookiename);
Object. Value=cookie value;
Response.Cookies.Add(object);//to store the cookies on client
machine






In memory cookie: the cookies which is stored in a
browser process memory is called as in memory cookie

cookie
client1
server
cookie
Browser
Browser
Request2+cookie
Res1+cookie
client2
request1
Res2+cookie
server
ASP.net
176




Retrieving information from a cookie:
syn1 :Http cookie object=Request.cookies[cookiename];
Variable=object. value;
Syn2:variable=Request.Cookies[cookie name"]. value;
note: in memory cookie automatically destroys themselves when
the browser is closed. So the default life span for in memory
cookie is till the browser is on.

Multivalue cookie inmemory cookie: a cookie which holds
multiple values in a single name are called as multivalue cookies.
To create a multivalue cookie:
syn:HttpCookie object=new HttpCookie(cookiename);
object.Values["key"]="somevalue";
//object.Values.Add("key","some value");
Response.Cookies.Add(object);//to store the cookie on the
client machine



Ex:






Button1_Click
{
HttpCookie h = new HttpCookie("a");//create a cookie
h.Value = "1000";
Response.Cookies.Add(h);//to store the cookie on client
machine
Label1.Text = "cookie is created";
}
Button2_Click
{
HttpCookie h = Request.Cookies["a"];
Label1.Text = "cookie value is :" + h.Value.ToString();
}


create
label1
display
ASP.net
177
To retrieve information from multi value cookie:
syn: HttpCookie object=Request.Cookies[Cookiename];
To get count
..
Object.Values.Count
To get keys

Object.Values.GetKey(index);
To get key value:
Object.Values[index];
Object.Values.Get(index);
For creating and retrieving information from multi value
cookie
Design :




Button1_Click
{
HttpCookie h = new HttpCookie("color");
h.Values["red"] = 10;
h.Values["blue"] = 20;
h.Values.Add("green", "30");
Response.Cookies.Add(h);
Label1.Text = "cookie is created";
}
Button2_Click
{
HttpCookie h = Request.Cookies["color"];
label1.Text="";
for (int i = 0; i < h.Values.Count; i++)
{
Label1.Text += h.Values.GetKey(i) + "=" +
h.Values[i].ToString() + "<br>";
}
}

create
label1
display
ASP.net
178


Out memory cookie: a cookie which is stored permanently on
the hard disc of a client machine is called as out memory cookie

When the client gives the first request cookie is created on the
server and along with the response it is send back to the client
and stores on the clients hard disc at the same time a copy of
that cookie is maintained on the browser process memory so
that it is reused along with the next request and the responses
The persistent cookies are maintained on the clients hard disc in
terms of a text file
The persistent cookie life span should be given by the
programmer and it automatically destroyed by the os of the
client machine when the life span is completed
Location: all the persistent cookies are store on
C:\documents and settings\administrator\cookies







cookie
hard disc
Browser
cookie
cookie
request1
Res1+cookie
Browser
Req2+cookie
Res+cookie
ASP.net
179
Creating single value persistent cookie:
Syn: HttpCookie obj = new HttpCookie("cookiename");
object.Value=some Value;
// mention expiry time
object.Expires=DateTime.Now.AddMinutes();
AddSeconds
AddHours
AddMonths
AddYears
AddDays
DateTime.MaxValue
Storing cookie on hard disc:
Response.Cookie.Add(object);
Creating multivalue out memory cookie:
//create a cookie
Http Cookie obj= new Http Cookie (cookie name);
Obj. Values [key]=some value;
//mention expiry date
Object.Expires =date.Now.AddMinutes(-----);
// to store the cookie on client machine
Response.Cookies.Add(Object);


Page_Load
{
Ex for persistent cookie






















Enter user name
Enter password


Remember username and password

ASP.net
180
if (Request.Cookies["uname"] != null &&
Request.Cookies["pwd"] != null)
{
if (Request.Cookies["uname"].Value.ToString() ==
"asp.net" && Request.Cookies["pwd"].Value.ToString() ==
"asp.net")
Response.Redirect("valid.aspx");
}
}
Button1_Click
{
if (TextBox1.Text = "asp.net" && TextBox2.Text ==
"asp.net")
{
if (CheckBox1.Checked == true)
{
HttpCookie u = new HttpCookie("uname",
TextBox1.Text);
u.Expires = DateTime.MaxValue;
Response.Cookies p = new HttpCookie("pwd",
TextBox2.Text);
p.expires = DateTime.MaxValue;
Response.Cookies.Add(p);
}
Response.Redirect("invalid.aspx");
}
}
We have to create valid.aspx and invalid.aspx
Drawbacks of cookie:
Cookies can be easily deleted on the client machine because
there is no security for cookies on the client
Cookies are not supported by all the browsers
Only limited no of cookies can be maintained on a client machine
i.e. 400 for every website only 20 cookies are allowed to create
Each cookie size should not exceed 1024 bytes
Maintaining the state in ASP .net





Query string: it Is used to pass the required data or value from
one webpage to other webpage or from one website to other
website
ASP.net
181
Def: a query string is a key and value pair which is appended at
the end of url address
Query string and url address should be separated using ?
Question mark
All values of query string are stored in the form of collection with
the name query string
The data type of query string variable is object type
Ex: to transfer the data from one webpage to another webpage
using query string

If we want to pass required data from default.aspx to
default2.aspx within the submit button click event we can write
To pass single value
Response.Redirect("Default2.aspx?a=10");
To pass two values
Response.Redirect("Default2.aspx?a=10 & b=20");
To pass three values:
Response.Redirect("Default2.aspx?a=10 & b=20&uname=sai");
Whenever we are passing one or more values from one webpage
to other webpage then a query string collection table is prepared
like Request.QueryString["a"]

Ex: to transfer the data from one webpage to another
webpage using query string
submit
Default.aspx
Source page

Default2.aspx
Target page
Empid
pkey
ASP.net
182

Key Value
A 10
B 20
Uname kanna

Within the destination page(default2.aspx) in the above example
we can trap the query string values like
Request.QueryString["a"] or Request.QueryString[0]
.>10
Request.QueryString[b"] or Request.QueryString[1]
.>20
Request.QueryString[uname"] or Request.QueryString[2]
.>kanna
Disadvantages of query string
As query string transfers the data in plain text format and data is
visible within the address bar query string cannot be used to
pass the sensitive information like password, etc
Maximum limitation for address bar of any browser window is 4
kb(4096 bytes), so we cannot transfer more than 4 kb of
information using query string (this 4kb uses url address also)



















ASP.net
183
Ex with query string:

Code for Default.aspx
Button1_Click
{
Response.Redirect("Default2.aspx?a="+ TextBox1.Text
+"&b=" + TextBox2.Text);
}
Code for Default2.aspx
Page_Load
{
TextBox1.Text = Request.QueryString["a"].ToString();
TextBox2.Text = Request.QueryString[1].ToString();
}







Enter value for a
Enter value for b


submit
Default.aspx
Enter value for a
Enter value for b


submit
label3
ASP.net
184









Code for default3.aspx
Button1_Click
{
Response.Redirect("Default4.aspx?dno="+TextBox1.Text);
}
Code for default4.aspx

SqlConnection con;
SqlDataAdapter da;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection("integrated
security=yes;database=kanna;data source=localhost");
da = new SqlDataAdapter("select * from empdetails where
deptno="+Request.QueryString["dno"].ToString(),con);
ds = new DataSet();
da.Fill(ds, "empdetails");
GridView1.DataSource = ds;
Default3.aspx
Example with database
Enter deptno
submit
Default3.aspx
Default4.aspx
xxx
Xxx
Xxx
Xxx
Deptno Sal Doj Designatio Ename
ey
ASP.net
185
GridView1.DataMember = "empdetails";
GridView1.DataBind();}

SESSION: a session is some information maintained on a server
machine
Session is accessible by all the WebPages of a website
A session is created separately for every user
Session supports server side state management where the
complete information is maintained on the server machine
For every client which gives the request to the server is
identified by the web server by creating a session for that
session a session id is created which is 120 bit hexa decimal
unique value.
Session id is a encrypted format and no hacker can perform
reverse engineering to it
To maintain this session id asp .net supports
1. Cookies
2. Urlencoding
Cookie: when the client gives the request a session is created on
the server and its session id is maintained in in-persistent cookie
on the client machine by sending it along with the response for
the next request and the response the session id is taken to the
server and the client
Login.asmails
px:

Enter username
Enter password


submit
Default.aspx
cancel
pk
ASP.net
186






The cookie which is maintained the session information the client
machine uses
ASP.net-SessionID as a name
2. url encodeing:the session id information can also be maintained
along with the url of the application where every request and the
response takes the session id between client and server
http://localhost/appname/(sessionid)/filename.aspx
3. To use this type of session maintenance we should go to
web.config file
<system.web>
<sessionState cookieless="true"/>
</system.web>
4. To create session manually asp. Net has provided a predefined
object or a property called as Page.Session
5. The session object is actually an object of
System.Web.Sessionstate.Httpsessionstate
6. the session objects provides some methods and properties
methods: Apattern
Add
Clear
Cookie



Asp.net-sessionid
Session id
Session id
Session
Request1
Response+SessionID
Request2+SessionID
Response2+SessionID
ASP.net
187
Remove
RemoveAll
RemoveAt
7. properties:Cookiemode
Count Mode
IsCookieless SessionId
Keys TimeOut
(specified the life span for session default life span for session is 20
minutes)
Creating a session:
Syn : Session[name of the session]=some value;
To get value variable=Session[name];






Page_Load(object sender, EventArgs e)
{
if (Session["Visit"] == null)
Session["Visit"] = 1;
else
{
int i = (int)Session["Visit"];
i++;
Session["Visit"] = i;
}
Label1.Text = "you have visited:" + Session["Visit"] + "time";
}
To disable the session for complete web application go to
web.config file
<system.web>
<pages enableSessionState="false"/>
</system.web>
To disable the session for a webpage
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="session1.aspx.cs" EnableSessionState="False"
Inherits="_Default" %>



label1 button1
ASP.net
188




ALL THE BEST






M.Umamaheswara Reddy

Uma9703050520@gmail.com

Anda mungkin juga menyukai