Covers Concepts Programs Authored by B.Kanna Babu: A Revolution in The Web Programming World
Covers Concepts Programs Authored by B.Kanna Babu: A Revolution in The Web Programming World
Covers Concepts Programs Authored by B.Kanna Babu: A Revolution in The Web Programming World
net
ASP.NET
A revolution in the web programming world
Authored by
B.KANNA BABU
1
ASP.net
Acknowledgements
2
ASP.net
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.6Intermediate Language
1.6.1Metadata
1.6.2 Code
1.6.3 Resource
1.6.4 Manifest
4
ASP.net
5
ASP.net
6
ASP.net
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
VERSIONS OF .NET:
Note: Microsoft has given a statement that some new frameworks are
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
10
ASP.net
11
ASP.net
ARCHITECTURE OF MS.net
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
12
ASP.net
.net application----compilation----IL---CLR---OS
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
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
15
ASP.net
Web
Dev WebPages
FLASH ASP.NET
IS
SERVELET
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….
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
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
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
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>
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
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
25
ASP.net
View source:
Form Tags:
26
ASP.net
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
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>
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>
BUTTON CONTROLS
30
ASP.net
SCRIPTING LANGUAGES:
• SCRIPTING LANGUAGES: these are used for dynamic client side web
applications
31
ASP.net
Java script
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
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
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
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>
36
ASP.net
37
ASP.net
38
ASP.net
39
ASP.net
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>
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>
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>
h1,
h2,h3,h4,h5,h6{
Color: red;
}
p{
background-color: pink;
}
46
ASP.net
View source:
47
ASP.net
@import url('style2.css');
p{
background-color:pink;
font-size:30;
font-family:arial;
}
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
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….
49
ASP.net
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
50
ASP.net
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
About IIS
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
53
ASP.net
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
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
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
58
ASP.net
• Application
• Server
• Cache
• Trace
• Ispostback etc……..
Coding techniques
59
ASP.net
60
ASP.net
Controls
HTML HTML
server Web server
61
ASP.net
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
System.Web.UI.HtmlControls .HTMlControl
HtmlInputButton
HtmlInputText HtmlGenericControl
HtmlInputFile HtmlinputImage
HtmlInputCheckBox HtmlinputTable
HtmlinputradioButton HtmlinputTableCell
HtmlinputTablerow
63
ASP.net
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:
65
ASP.net
LABEL3
Properties:
textbox1:autopostback=true
view source:
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
Enter ur name
Enter hobbies
dancing playing
Browsing chatting
LABEL -3
SUBMIT
View source:
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;
}
68
ASP.net
69
ASP.net
• Example:
70
ASP.net
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
73
ASP.net
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
Button Controls:
74
ASP.net
BUTTONS
PUSH BUTTON
LI NK BUTTON I MAGE BUTTON
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
textbox1
View source:
76
ASP.net
TextBox1.BackColor = System.Drawing.Color.Green;
}
protected void Button3_Click(object sender, EventArgs e)
{
TextBox1.BackColor = System.Drawing.Color.Blue;
}
Arithmetic problem.aspx
Enter first no
txtNum1
Enter second
txtNum2
no
txtResult
Result
Add
subtract Multiply Divide
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
button1 button2
View source
79
ASP.net
Arithmetic problem.aspx
Result txtResult
Listing Controls
80
ASP.net
81
ASP.net
82
ASP.net
83
ASP.net
Validation controls
84
ASP.net
• 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
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
Properties:
Go to toolbox drag and drop Regular expression validator.
Validation expression=select internet url address
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
Agpassword
Retype Range validator
Compare validator
Example:
Submit summary Validation summary
Drag and drop validation
89
ASP.net
Enter username
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");}
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
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 :
92
ASP.net
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
95
ASP.net
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
97
ASP.net
I- layered approach
FEa
pplication
BEa
plpication
II- layered approach:
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
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
Machine2/tool2
ADO. Net
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
10
ASP.net
10
ASP.net
10
ASP.net
1. Makes a connection
2. Pass some query and get result back
• 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
10
ASP.net
10
ASP.net
8. Dataset Dataset
9. DataTable DataTable
10
ASP.net
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
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. 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
10
ASP.net
la b e l1 DELETE
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
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
id=sa;password=sa;database=kanna;data source=localhost");
con.Open( );
SqlCommand cmd;
empid="+TextBox1.Text,con);
cmd.CommandType = CommandType.Text;
11
ASP.net
int i = cmd.ExecuteNonQuery( );
con.Close( );
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
DISCONNECTED ARCHITECTURE:
11
ASP.net
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
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
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
• 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
Add new
5
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;
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
</div>
• 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>
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
• 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
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
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();
}
}
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();
}
</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;
}
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" />
<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>
</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;
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)
{
R.Checked = false;
}
}
}
ADROTATOR CONTROL
Example:
Step-1: create website--add existing item--add three
image
</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
}
.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
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
Design :
stor
label
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
COOKIES
COOKIES
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();
}
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>";
}
}
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
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
Default.aspx Default2.aspx
Source page Target page
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)
Default.aspx
submit
submit
submit
Default4.aspx
Default3.asp
Designatio
Ename n Doj Sal Deptno
Xxx
Xxx
Xxx
xxx •
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
Asp.net-sessionid
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.