Covers Concepts Programs Authored by B.Kanna Babu: A Revolution in The Web Programming World

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 185

ASP.

net

ASP.NET
A revolution in the web programming world

Covers Concepts Programs

Authored by

B.KANNA BABU

1
ASP.net

Acknowledgements

I want to acknowledge my deep gratitude to


Mr.T.S.S.sunil Kumar and Mr.G.Sudhakar who
encouraged me a lot for their cooperation
Iam also thankful to Mr.Ganesh, Mr.satyanarayna
Mr.Thandava Krishna, Mr.Manik basava, Mr. Joji babu
who has provided staunch support throughout the
project and helped me to complete this book successfully
Some errors may have inadvertently crept in this
book. despite my best efforts to keep them out. Readers
are therefore encouraged to point out these errors so
that they are not repeated in the next
edition.suggesitions to improve the book are also
welcome.mail me at [email protected]

2
ASP.net

About the Author

Mr.B.kanna Babu has been associated


with teaching Microsoft Technologies
As a corporate trainer for a couple of
organizations. he worked at various
colleges as professor and he has
participated in many technical paper
presentations

3
ASP.net

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.6Intermediate 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

4
ASP.net

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

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

5
ASP.net

7 Internet information service(IIS)


8 Working with ASP.net Applications
8.1 Why ASP.net
8.2 Evolution of ASP.net
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

6
ASP.net

11.2.5 Validation Summary with Example


11.2.6 Custom validator with Example
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

7
ASP.net

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

MICROSOFT.NET

8
ASP.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…

9
ASP.net

MICROSOFT.NET

.NET FRAMEWORK
.NET PRODUCTS .NET Services .NET Servers
It is the layer
MSVisual studio • Passport service • MSSQL Server
between Application
editor MS Simulator • Calendar service • BizTalk server
and OS
• Contact Service • IIS
It consists of
• Alert Service • Mobile IIS
1. CLR
• Web • Exchange server
2. BCL
service Etc…. • Internet Security Serve
Etc……..

Tools:-
compiler
Interpreter
Debugger
Assembler
and

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

10
ASP.net

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

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

11
ASP.net

ADO.NET is used for database handling


WEBSERVICES are used for complete distributed applications

ARCHITECTURE OF MS.net

C#.net Vb.net J#.net


Base Data I Security
WindowsXML
class layer
Application layer Threadin
Web Mobile Service
applicat applicat web applicat
applicat

Memor CLR Monitori


y ng
The
Securi
Translating layer ty

ARCHITECTURE OF MS.NET
O
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

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

12
ASP.net

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
COD
PE WRAPPER
RESOURC

MANIFES

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

13
ASP.net

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

CLR
ILLOADER

ACCESS

CONTROLER CTS

CLS

CAS RBS
MEMORY
MANAGEMENT

JITCOMPILER

• 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

• 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
14
ASP.net

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
• 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)

15
ASP.net

Web

Dev WebPages

Static HTML Dynamic


PHOTOSHOP client side Server
DHTM ASP

FLASH ASP.NET

IS

SERVELET

• 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

16
ASP.net

• 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

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

17
ASP.net

• 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

Basic tags: these tags will provide the structure of the document
Ex:
<html>
<head>
<title>HELLO</title>

18
ASP.net

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

link
h1

F1.html
F2.html
• Cross link: it is used for linking same document different paths
• Anchor tag is used for linking

Ex for hyper link


<html>

19
ASP.net

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

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

20
ASP.net

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">
<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

21
ASP.net

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

Ex for multi media tag:

22
ASP.net

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>

Font tags:
Syn :<font face=“value” size=“value” color=“value”>
</font>

23
ASP.net

• Font tags:
Syn : <font face=“value” size=“value” color=“value”>
</font>

Arial
1leastsize
MonotypeCors
2
iva
3defaultsize
TimesNewRo
4
man
5
6
7highestsize

Example with font tags

View source

<Html>

24
ASP.net

<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

Ex with Frame Tags

25
ASP.net

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>

Form Tags:

FORM TAGS: it is used to design some webpage by placing some controls

26
ASP.net

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

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

27
ASP.net

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>

EX with Form tags

28
ASP.net

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>

<td><INPUT TYPE="PASSWORD" NAME="T3"></td>


<tr><BR><tr>
<td>SELECT GENDER : </td>

29
ASP.net

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

BUTTON CONTROLS

• RESET BUTTON: it is used for providing a webpage with default


settings

30
ASP.net

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”>

SCRIPTING LANGUAGES:

• SCRIPTING LANGUAGES: these are used for dynamic client side web
applications

31
ASP.net

• 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

Java script

 JavaScript is the premier client-side scripting language used


today on the Web.

32
ASP.net

 It’s 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

• To add JavaScript to your webpage place the tag


<script language=“JavaScript’>
Ex:

33
ASP.net

<html>
<script Language=“JavaScript’>
Document. Write (“welcome”)
</script>
</html>

VARIBLES IN JAVASCRIPT
 JavaScript doesn’t support any predefined data types that’s 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>

Functions in javascript:

Prompt function:
It is used to accept any data from the user.
Variable=prompt (“message”)

34
ASP.net

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]
}
• 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

35
ASP.net

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)
{
………………..
……………}

When data types of arguments are changed:

When data types of args are changed


If we take function like
Add(int a,int b)
{
………………..
………………
}

36
ASP.net

• 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

37
ASP.net

• 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
• 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

38
ASP.net

• 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

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

39
ASP.net

• 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

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

40
ASP.net

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>
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{
……………………

41
ASP.net

…………………..
}

Example:

View source:

<html>
<style type=text/css>

h1{
background-color:khaki;color:red;
}
h3{
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{
…………………
……………….

42
ASP.net

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

View source:
<html>
<style
type=text/css>
input{
font-size:10;
}
.t{
background-color:yellow
}
</style>
<center>
<h1>LOGIN FORM</h1>

43
ASP.net

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

• 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

44
ASP.net

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>

45
ASP.net

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:

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

46
ASP.net

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

47
ASP.net

@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
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

48
ASP.net

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

 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

49
ASP.net

 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 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 doesn’t 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

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

51
ASP.net

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 ASP.net is language
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 forASP.net supports only IIS
execution IIS,PEARL,PERSONAL web
server
6. It depends on HTML controls It provides its own controls
7. It does not supports structured error It supports structured error
handling handling
8. It depends on com tech for database It uses .net framework class
and file handling libraries for database and file
handling and com
components
9. It is interpreted technology It is compiled technology
10. .asp .aspx

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

52
ASP.net

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

53
ASP.net

Visual studio editor-2008


Open dotnet in by typing devenv in command prompt

 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

54
ASP.net

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
 Solution explorer window
 Server explorer window
 Tool box
 Property window
 Error List

55
ASP.net

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

LIFE CYCLE EXECUTION OF ASP.net

56
ASP.net

L ife c y c le e x e c u ti o n o f A S P .n e t a p p li c a tio n

re q u e s
h ttp ://lo c a lh o s t/c o d t a s p x IIS In e tin fo .e
e1.
c lie a s p n e t_ is .d ll
nt

a s p n e t_ w x e

A S P . n e t w o rk p r o chetst ps p ip e lin e s

p ro c e s s
O /p d is p la y
o /p

CLR
w p .e xew o rk p ro c e
ss serve
r

• 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

57
ASP.net

• 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
• 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

58
ASP.net

• Application
• Server
• Cache
• Trace
• Ispostback etc……..

Coding Techniques in ASP.net:

Coding techniques

Code inline model Code behind modell

Designing Designing Programmin


. code code g
A code
S
P .aspx
x Programmin .aspx.cs
g
code

• 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:

59
ASP.net

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

60
ASP.net

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

61
ASP.net

• 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

s n o C o n tro l n a m C la s s n a m e Tag
e
1 In p u t( b u t)t o n H tm lin p u tB u tto n < in p u t ty p e = b u tto n
>
2 In p u t( R e )s e t H tm lin p u tB u tto n < in p u t ty p e = r e s e t>
3 In p u t( s u b)m it H tm lin p u tB u tto n < in p u t ty p e = s u b m
it>
4 In p u t( T e) x t H tm lin p u tT e x t < in p u t ty p e = T e x t>
5 In p u t( p a s s w) r dH tm lin p u tT e x t <in p u tty p=ep a s s w o
o rd >
6 In p u t(f)ile H tm lin p u tF ile < in p u t ty p e = F ile >
7 In p u t( C h e) c k H tm lin p u tC h e c k B o x <in p u tty p=Ce h e c k
B >o x
8 In p u t( R a )d io H tm lin p u tR a d io B u tto < in p u t ty p e = R a d io
n >
9 Im a g e H tm lIm a g e < im a g e >
1 0 T a b le H tm lT a b le < ta b le > , < t dt>r>, <
H tm lT a b le C e
ll H tm lT a b le R o
w lC o
1 1 H o r iz o n ta l R l eHrt m lin p u tG e n e r ic c o o<l h r >
u n tr

62
ASP.net

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 HtmlGenericControl
HtmlInputFile HtmlinputImage
HtmlInputCheckBox HtmlinputTable
HtmlinputradioButton 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,
• Textbox 2, Button 1,Button 2 are objects to the respective classes

63
ASP.net

• 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 atServer side
client side
2 Donot provide state provide state management
management
3 Donot contain any class for Contains separate any class for
the control each control
4 Donot support oops support oops concepts
5 Can make to run at server By default it is server side control
side by adding
runat=“server”

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

Controls in ASP. net:


Different controls that are available in ASP.net are

64
ASP.net

• 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

example with label and textbox :

65
ASP.net

WELCOME TO ASP.NET LABEL1

LABEL2 ENTER YOUR TEXTBOX

LABEL3

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

66
ASP.net

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;

67
ASP.net

}
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

68
ASP.net

• User request can be redirected to any webpage or to any website we


use two ways
• Using design controls directly
• By using the code

Redirecting user request

Using design Using coding


controls
Hyperlink Response.
Link button Redirect Server.
Image button

 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

69
ASP.net

• 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

70
ASP.net

• 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

71
ASP.net

• 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

72
ASP.net

Differences between Hyperlink link button and image button

Hyperlin Link button Image Button


k

Link can Link can be created to theLink can be created to the


be created text only and cannot beimage only and cannot be
to the text created to the image created to the text
and also
to the
image

It doesnot support command namesupport command name an


support an command argumentscommand arguments
command properties properties
name an
command
arguments
properties

73
ASP.net

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 Used to redirect to any
any website present in the same webpage in any website
webserver present in the same webserver
or in different webserver

Execution is fast Execution is slow


Cannot be user to pass any values to Can be user to pass any values
the destination page to the destination page

Button Controls:

• ASP. net has provided three button controls for submitting


information to the server

74
ASP.net

BUTTONS

PUSH BUTTON
LI NK BUTTON I MAGE BUTTON

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

75
ASP.net

person
events Eating
Drinking
singing
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

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)
{

76
ASP.net

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

Example2 with click event:

Arithmetic problem.aspx

Enter first no
txtNum1
Enter second
txtNum2
no
txtResult
Result

Add
subtract Multiply Divide

cmdAdd cmdSubtract cmdMultiply cmdDivide

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();
77
ASP.net
}

78
ASP.net

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)


{
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

79
ASP.net

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

Arithmetic problem.aspx

Enter first no txtNum1


Enter second txtNum2
no

Result txtResult

Add subtrac Multiply Divide


cmdAdd cmdSubtract cmdMultiply cmdDivide
View source: assignment

Listing Controls

80
ASP.net

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

81
ASP.net

82
ASP.net

83
ASP.net

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 beforeValidating a webpage on the server


submitting the information isafter submitting the information is
called as client side validation called as server side validation

2. It can be perform using clientIt can be perform using the code


side script code return usingplaced on a server return by any
scripting languages .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

common properties for all validation controls:


• ControlToValidate =some control id
• Error Message=some text
• Text=some message

84
ASP.net

• 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 doesn’t 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

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

85
ASP.net

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

Properties:
Design: drag and drop range validator
Properties of range validator are
Control to Validate=TextBox2
Error Message=invalid age
Maximum value=25

86
ASP.net

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

Properties:
Go to toolbox drag and drop compare validator
Control to validate=TextBox2
Control to compare =TextBox1
Operator=equal
Type: string,

87
ASP.net

• 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

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

88
ASP.net

• 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


password Required fiels

Agpassword
Retype Range validator
Compare validator
Example:
Submit summary Validation summary
Drag and drop validation

• 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

89
ASP.net

• Example using custom validator to perform client side validations

Enter username

Enter password Custom validator

submit

• Properties
• Control to validate=textbox2.text
• Error message=password should contain min of 6 characters
• Client validation functions =F1

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
{ 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

90
ASP.net

• 1st arg will store the type of the control from which function has been
called
• 2nd 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)
{

}
protected void CustomValidator1_ServerValidate(object source,
ServerValidateEventArgs args)
{
if (args.Value == "kanna")
{
args.IsValid = true;
}
else

91
ASP.net

{
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
step4:add home.aspx aboutus.aspx contactus.aspx to the existing
project

92
ASP.net

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

Example:

93
ASP.net

• 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>

94
ASP.net

Step-5: select menu copntrol --properties---datasourceid=new


datasource---select sitemap---ok.
Step-6: debug and check the output

95
ASP.net

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;

ADO.net

96
ASP.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

Disadvantages of I-layered approach:


Does not support centralized database
Cannot withstand large amount of data

97
ASP.net

I- layered approach

FEa
pplication

BEa
plpication
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:
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:

98
ASP.net

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

Machine1/tool1

Ex:VB,power builder,
FE app D2k/oracle forms
JAVA,. net

Native drivers
DAO
RDO
ADO
ADO. net Ex:OLEDB
ODBC
middleware JDBC

Native drivers Ex:MS ACCESS


MS SQLSERVER
BE applications ORACLE
MYSQL etc…

Machine2/tool2

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

99
ASP.net

FEap
coa
ip
ntl O
m
ectbjodel D
ve
irr
D
ab
atse

DAO RD O ADO
ADO
net. ODBC
OL
EDB
SQLCLI

• 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

10
ASP.net

ADO versus ADO.NET (continued)

Feature ADO ADO.NET


XML XML aware XML is the native transfer
capabilities medium for the objects

Firewalls Firewalls block systemlevel XML flows through the firewall


COM marshalling via HTTP

Code Coupled to the language Managed code library – Uses


used, various implementation 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 Uses RECORDSET object Uses DATASET object


memory (contains one table) (contains one or more
DATATABLE objects)

Disconnected Uses CONNECTION object Uses DATASETCOMMAND


access and RECORDSET object with object with OLEDB
OLEDB

Disconnected Uses COM to marshal Transfers DATASET object via


access across RECORDSET XML. No data conversions
multitiers required

10
ASP.net

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

10
ASP.net

1. Makes a connection
2. Pass some query and get result back

3. Disconnected from the database system


client 4.Makes the connection again server
5. Pass some other query and get result back

6.Disconnected from the database system

• 2nd 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

1 db 1

2 2
4 3
U 3 UI
N/W 4
I N/W
buffer 5
5 buffer

Client-1
server Client-2
• 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

10
ASP.net

• Data providers in ADO .net

Provider Sqlclient Oracle OLEDB ODBC


name client
Namespace System.Data. System.Data. System.Data.Oledb System.Dat
sqlclient oracleclient a.Oledb

Database Only Only oracle Any database for Any


connection sqlserver whicholedb drivers database
are present for which
odbc
drivers are
present

Code Managed Managed Unmanaged code Unmanage


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

10
ASP.net

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

Oledb Data adapter

ODBC Data adapter

10
ASP.net

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
• 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

10
ASP.net

• 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

Example with connection object:

View Sqlserver/sqlclient
source: Sqlserver/oledb
using System.Data.SqlClient;
label

10
ASP.net

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
• 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:

10
ASP.net

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 It works with only non- It works with only
queries action queries non-action queries
INSERT,UPDATE,DELETE that include
aggregate function

2. Returns no of rows Returns the total rowsReturns first row and


affected by the query data selected by thefirst column value of
query the query result

3. Return type is integer Return type is collection of Return type is object


rows or table

4. Return value is optionalReturn value is Return value is


and can be assigned tocompulsory and should becompulsory and
an integer variable assigned to anothershould be assigned
object to another knownto a variable of
as Data Reader required data type

Example with command object to delete a record:

10
ASP.net

la b e l1 DELETE

Step1: design the above screen

Step-2: go to database and create table

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)

11
ASP.net

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

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:

11
ASP.net

E n t e r e mp i
d

la b e l2 DELET

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;

11
ASP.net

int i = cmd.ExecuteNonQuery( );

con.Close( );

Label2.Text = i + "records deleted";

Example3:
Insert, update and delete

Design:

11
ASP.net

Enterempid

Enterempname

Enterdesignation

EnterDOJ

Entersalary

Enterdeptno

label7

insert
updat Delete
e

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 +
"')";
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;

11
ASP.net

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>");
}

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:

11
ASP.net

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

1 1
UI UI
db
3 2 2 3

PA PA
4 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

Second method:

11
ASP.net

DISCONNECTED DATA CYCLE

req C
data adapter O

N
applicatio
client n
data adapter N db
respo
E
dataset C
Db server
Client-1 ADO. net

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.

11
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.
E m p id Enam D e s i g n a iDo on j S a la ry D e p tn o
e t
101 EKm
a npnda ePt rao ij el sc t l a1d/ 1 / 2 0 0 4 0 0 0 0 10
0 e 7
102 S u n il T e a m l e d2 / 2 / 2 0 0 3 0 0 0 0 10
a 7
0
1 103 M u r a l i P r o g r a mm3 /e3r/ 2 0 0 2 0 0 0 0 10
7
104 C h a k r D e v e l o p 5r / 5 / 2 0 0 1 0 0 0 0 10
i e 7
105 bobby DBA 1 /1 /2 0 02 2 0 0 0 30
8

1 dept

D e p t n oD n a m e Location
0K a n n a Hyd
0S u n i l BangloreDelhi
0M u r a l i Vizag
0C h a k r i

D a ta s e t
1 .D s . T a b le s  E mp d e ta ils E m p D e ta il
dept sD e p t
D s . T a b[ 0l
e] s o r
E m p D e ta i
D s . T a b lEe p[ “d e t”a] i ls
ms D s . T a b[ l s
Id e n tific a tio n o f
0l e] s
O rD s . T a b[ “lEe ms p d e ”t a] i l s

D s . T a b[ 1l e] s
Dept
O rD s . T a b[ “l eDse p t
”]

• A s d a ta s e t c o n ta in s c o lle c tio n o f ta b le s e a c h ta b l
e is id2 . id e n tific a tio n o f ro w s
• A s e v e ry ta b le c o n ta in s c o lle c tio n o f ro w s e a c h ro w is i
• Ex:
D s . T a b[ 0l e] .sR o w s [ 1 ]
Emp d E n a e D e s ig n t iDo no j S a la r y D e p t n
i m a o
101 K a n n a P r o j e c e a1 d/ 1 / 0470 0 0 1 0

D N OD n a m e a tl ioocn
D s .T a b l e s [ 1 ] . Ro w s [
30 raju delhi
3. I dentification of columns:as every table contains collection each column is identified using index value
or column name
ex:Ds.Tables[0].columns[2]

Programmer
T
4. identification of cell or a ce ed using matrix notation by using either rows collection
or columns collection S is
ll data: a PL
cell
identifi
ex:Ds.Tables[0].columns[3
or DBA
Ds.Tables[0].columns[1][3]

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”);
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
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
2
1

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 103 Murali PM 3/3/07 30000 10


cancel 4
20
Edit 104 chakri testing 4/1/07 10000

Edit 105 Karee developer 6/1/07 8000 10

Add new
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
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 doesn’t provide designing facilities
• Repeater control doesn’t provide editing facilities
• Repeater control doesn’t 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:

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,"designation")
%></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;

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
• 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

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>

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();}}
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>
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();

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

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;
SqlCommand cmd = new SqlCommand(s, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GetData();
}
}

N o te :
totraptherow:datalistcommand eventargs class
h a s ap r o p e r t y S O E . I t e m w i l l s t o r e t h e r e s p e c t i v e r
o w i n w h i ci.e . if u s e r c lic k s o n 1 0 3 e m p id re c o rd d e l
e te b u tto n th e n

d e le t e 1 0 3 K a n n a T L 1 2 /1 1 /2 0 0 9 4

T o t r a p t h e la b e l:
W e u s e a f u n c t io n k n o w n a s F in d C o n t r o l
F in d c o n t r o l f u n c t io n w ill r e t u r n adnayt act y
• E d itin g th e d a ta u s in g d a ta lis t c o n tro l:
• n o t: ea s l o n g a s E d i t I te1 mD Ien ds e xt ei sd i t i t e m d a t a l i s t
d a ta ism o d e
• T o d is p la y d a ta lis t d a ta in e d ita b le m o d e th e n s e t
• D A T L IS T IN S T A T IC M O D E
E D I T / AE MV I DE N A DE E S I G N TDI OO s a la ry D e p tn o
S
EP M A NJ

E D IT 1 0 1 X x x Xxx Xxx Xxx Xxx


E D IT 1 0 2 X x x Xxx Xxx Xxx Xxx
E D IT 1 0 3 X x x Xxx Xxx Xxx Xxx
E D IT 1 0 4 X x x Xxx Xxx Xxx Xxx
E D IT 1 0 5 X x x Xxx Xxx Xxx xxx

• D A T A L IS T IN E D IT A B L E M O D E
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" />
</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;
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;
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();
}}
}

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
• 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

• Events associated with Grid View control:

s.no EventName ClassName Properties Description


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

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>

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();
}
}

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)
{
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();
}
}

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: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)
{
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:

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.pimage") %>' 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: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)
{

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;

}
}

}
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>
</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>
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();
}
Step-6 : press f5 and check the output
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

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

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" %>

Step-5: execute default.aspx and Default2.aspx and check the output


the skin file is applied to every page

o/p:
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

Step-3: paste the content place holder in C


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

Step-6: execute the default page and execute.

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

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
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.csok
• 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;
} }}

Design :
stor

label

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;
}

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

Button1_Click
{
String lb = ListBox1.SelectedItem.Text;
bool cb = CheckBox1.Checked;
//Response.Redirect("urlencodeing2.aspx? L="+lb+"&C="+cb+);
Server.Transfer("urlencodeing2.aspx");
}
Page_Load
{
// String lb = Request.QueryString["L"];
// String cb =
Request.QueryString["C"]; String lb =
Request.Params["ListBox1"];
String cb = Request.Params["CheckBox1"];
LabeIlt1e.mTe1xt =
"Lis t Biosxisvaclhueckis:b"o+x lb;
T h
Label1 .TeIxt tem+=2} "<br>CheckBox Value is :"
+submit
cb;
Item3
Item4
item5

label

• 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

COOKIES
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 valumeulti valuSeingle value Multi value


• 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:Http C o o k i e
object=renqBeuro wHs ttpCookie(cookiename);
west 1
er
Object.
Value=cookie value;
Response.Cookies.ARdeds(1o+bcjoeocktie);//to store
ctohoekiecookies on client machine cookie
client1 Request2+cooki

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


process memory is called as in memory cookie
Browser

Res2+cookie server
serve

c lie n t2
Retrievin g i n formation 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.
Ex:
creat displa

Button1_Click
{ label
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();
}

• 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

• 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 :

creat displa
label
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>";
}
}

• Out memory cookie: a cookie which is stored permanently on


the hard disc of a client machine is called as out memory cookie

Browser

cookie
hard disc
cookie

Browser

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
• 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);
Enter user name
Ex for persistent cookie
Enter password

Remember username and password


Res+cookie

Page_Load
{
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
• 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

Default.aspx Default2.aspx
Source page Target page

Ex: to transfer the data from one webpage to another


webpage u s i nsgu bqmui t ery 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"]

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)

• Ex with query string:


Default.aspx

Enter value for a


Enter value for a
Enter value for b
Enter value for b

submit
submit

• 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();
}
Default3.aspx

Example with database



Enter deptno

submit

Default4.aspx
Default3.asp
Designatio
Ename n Doj Sal Deptno
Xxx
Xxx
Xxx
xxx •

• 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;
GridView1.DataMember = "empdetails";
GridView1.DataBind();}

Default.aspx

Enter username

Enter passpwkoerdy
label3
Empid
in.as mailscancel
Log pkey
px:
submi

• 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
Request1
Cookie
Session
Session id Session id
Response+Session ID

Asp.net-sessionid

• 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
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”];

label button
1
Page_Load(object sender, EventArgs 1
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" %>
ALL THE BEST

B.KANNA BABU.

You might also like