Escolar Documentos
Profissional Documentos
Cultura Documentos
INTRODUCTION
ASP 2.0 using c# or VB.net
Database SQL Server, Xml
.Net Architecture
ASP.Net web Application
BCL
Windows Application
CLR
OS
BCL Base class language
CLR Common Language Runtime
OS Operating System
CLR
It is an environment which manages the execution of coding. It manages:
Memory management
Garbage collection
To support multiple language
(Note: difference b/w CLR n JVM is that JVM only support single language i.e. java)
BCL
Collection of standard class or common class which we can use .net supported language
E.g. - in VB.Net we use integer n in c# we use int but we can use int16, int32 in
both.
Note: ASP.net it is just a technology that runs on server with some language.
We must have common language specification for compiler to run .net.
Why .Net?
Powerful
Reusability
For web application not for desktop
-2-
In web development application run on server. At client side there is simple Html
page which is understand by a browser
.net is not platform independent so we must have Microsoft OS on the server and
anything on client coz client only have HTML page
.Net Framework
C1
C#
C2
-3-
MSIL
JIT
Native code
J#
C3
Advantages of JIT:
Types of JIT:
PRE
ECHNO
NORMAL
-4-
Server
IIS (Internet information service) it is used with 1.1 version
It is not loaded on XP-home edition
We can load it through
Control panel --- add remove files--- windows components
To change home directory
Control panel --- adm tools --- IIS --- CS ---web sites--- default web site
(Right click)--- Properties --- home directory
First application
File new website ASP.Net web site
Location (specify server) file system (web server)
HTTP (IIS)
Language
Visual basic
C#
Extension
.aspx
designing or presentation
.aspx.vd code file (VB)
.aspx.cs code file (C#)
Concept of Partial class is introduced in ver 2.0 which means we can divide the
class into number of parts. Benefit of this system code(used by system) can be
store in one partial class n developer code in another.
-5-
Page load event is fired first without even calling this event. It has to parameters
1st for reference and 2nd for manage event data
Windows required
Solution explorer
Toolbox
HTML Control (background compatibility)
Run on client side and are browser dependent
Web Server control
Run on server side and are browser independent
Property window(f4)
Two types of layout
Grid layout (available in ver 1.1)
Flow layout (available in both version)
Advantages we work as notepad, page will be light
Weighted due to less labels
Ctrl + space for intelligence help.
Difference b/w property n variable is that property can be read only, write only,
we validation n checks can be used but with variables these r not possible.
Program 1:
-6-
To compile line by line click in front of line where u want to place break and then
press f10.
To add two numbers
Textbox3.text = convert.Toint32(textbox1.text) +
convert.Toint32(textbox2.text);
In C#
Textbox3.text=convert.Tostring(convert.Toint32
(textbox1.text) +convert.Toint32(textbox2.text));
To use common handle i.e. one procedure handling more then one event we add
handles in the end of procedure in Vb.net like
Handles button3.click,button4.click, button5.click
If sender is button 3 then
Sum
Else if sender is button4 then
Mul
Else
Divide
In C#
We change in HTML, use onClick method for this purpose
-7-
Some people like VB.NET's natural language, case-insensitive approach, others like C#'s
terse syntax. But both have access to the same framework libraries. We will discuss about
the differences in the following topics:
1.
2.
3.
4.
5.
-8-
Keyword Differences
Purpose
Declare a variable
VB.NET
Private, Public, Friend,
Protected, Static1,
Shared, Dim
C#
(keywords include userdefined types and built-in types)
declarators
Const
const
Declare a named
constant
new
Create a new object New, CreateObject()
Sub
void
Function/method
does not return a
value
Overload a function Overloads
(No language keyword required for
or method (Visual
this purpose)
Basic: overload a
procedure or method)
this
Refer to the current Me
object
MyClass
Make a nonvirtual
n/a
call to a virtual
method of the current
object
GetChar Function
[]
Retrieve character
from a string
Declare a compound Structure <members> End struct, class, interface
Structure
data type (Visual
Basic: Structure)
Initialize an object Sub New()
Constructors, or system default type
(constructors)
constructors
Terminate an object n/a
n/a
directly
Method called by the Finalize
destructor
system just before
garbage collection
reclaims an object7
-9-
Initialize a variable
where it is declared
Dim x As Long = 5
Dim c As New _
Car(FuelTypeEnum.Gas)
// initialize to a value:
int x = 123;
// or use default
// constructor:
int x = new int();
delegate
- 10 -
Const
Declare a class
constant
Derive a class from a Inherits C2
base class
Override a method Overrides
Declare a method that MustOverride
must be implemented
in a deriving class
Declare a method that NotOverridable (Methods
can't be overridden are not overridable by
default.)
Overridable
Declare a virtual
method, property
(Visual Basic), or
property accessor
(C#, C++)
Shadowing
Hide a base class
member in a derived
class
Declare a typesafe Delegate
reference to a class
method
WithEvents
Specify that a
variable can contain
an object whose
events you wish to
handle
Specify the events for Handles (Event procedures
which an event
can still be associated with a
procedure will be
WithEvents variable by
called
naming pattern.)
Evaluate an object With objExpr
<.member>
expression once, in
<.member>
order to access
End With
multiple members
Structured exception Try <attempt>
Catch
handling
const
Decision structure
(selection)
Decision structure
class C1 : C2
override
abstract
sealed
virtual
n/a
delegate
n/a
n/a
<handle errors>
Finally
<always execute>
End Try
- 11 -
for, foreach
Redim
Reallocate array
Visible outside the Public
project or assembly
Invisible outside the Friend
assembly (C#/Visual
Basic) or within the
package (Visual J#,
JScript)
Visible only within Private
the project (for nested
classes, within the
enclosing class)
Accessible outside Public
class and project or
module
Accessible outside Friend
the class, but within
the project
Private
Only accessible
within class or
module
Protected
Only accessible to
current and derived
classes
Preserve procedure's Static
local variables
Shared
Shared by all
instances of a class
'
Comment code
n/a
Case-sensitive?
Call Windows API
Yes
use Platform Invoke
Rem
- 12 -
No
Declare <API>
public
internal
private
public
internal
private
protected
n/a
static
//, /* */ for multi-line
/// for XML comments
comments
event
lock
goto
VB.NET
C#
Decimal
decimal
Date
DateTime
String
string
Byte
byte
Boolean
bool
Long
long
Single
float
Double
double
int
Operators Differences
Purpose
Integer division
Modulus (division
returning only the
remainder)
Exponentiation
Integer division
Assignment
- 13 -
VB.NET
C#
Mod
n/a
\=
/=
Concatenate
Modulus
Bitwise-AND
Bitwise-exclusive-OR
Bitwise-inclusive-OR
Equal
Not equal
Compare two object
reference variables
Compare object
reference type
Concatenate strings
Shortcircuited Boolean
AND
Shortcircuited Boolean
OR
Scope resolution
Array element
Type cast
Postfix increment
Postfix decrement
Indirection
Address of
&= NEW
+=
n/a
n/a
n/a
n/a
%=
==
<>
!=
Is
==
TypeOf x Is Class1
x is Class1
&
AndAlso
&&
OrElse
||
. and base
[ ]
AddressOf
Logical-NOT
One's complement
Prefix increment
Prefix decrement
Size of type
Bitwise-AND
Bitwise-exclusive-OR
Bitwise-inclusive-OR
Logical-AND
Logical-OR
Conditional
Pointer to member
Not
Not
n/a
n/a
n/a
++
And
&
Xor
Or
And
&&
Or
||
If Function ()
?:
n/a
&=
^=
|=
()
Cint, CDbl,
..., CType
n/a
n/a
n/a
Programming Difference
- 14 -
(type)
++
-*
-sizeof
Purpose
Declaring
Variables
Comments
VB.NET
C#
Dim x As Integer
Public x As Integer = 10
int x;
int x = 10;
' comment
x = 1 ' comment
Rem comment
Assignment nVal = 7
Statements
Conditional If nCnt <= nMax Then
' Same as nTotal =
Statements
' nTotal + nCnt.
Selection
Statements
nTotal += nCnt
' Same as nCnt = nCnt + 1.
nCnt += 1
Else
nTotal += nCnt
nCnt -= 1
End If
Select Case n
Case 0
MsgBox ("Zero")
' Visual Basic .NET exits
' the Select at
' the end of a Case.
Case 1
MsgBox ("One")
Case 2
MsgBox ("Two")
Case Else
MsgBox ("Default")
End Select
// comment
/* multiline
comment */
nVal = 7;
if (nCnt <= nMax)
{
nTotal += nCnt;
nCnt++;
}
else
{
nTotal +=nCnt;
nCnt--;
}
switch(n)
{
case 0:
Console.WriteLine("Zero");
break;
case 1:
Console.WriteLine("One");
break;
case 2:
Console.WriteLine("Two");
break;
default:
Console.WriteLine("?");
break;
}
Hiding
Base Class
Members
- 15 -
End Sub
End Class
System.Console.WriteLine(
"Test in BaseCls");
}
}
public class DervCls :
BaseCls
{
// The hiding element
public new string Z = "*";
public new void Test()
{
System.Console.WriteLine(
"Test in DervCls");
}
}
WHILE
Loops
- 16 -
' Test at
While n <
' Same
n += 1
End While
start of loop
100 .
as n = n + 1.
'
System.Console.WriteLine(
"Accessed through" +
" derived class:{0}",
DObj.Z);
BObj.Test();
DObj.Test();
}
}
while (n < 100)
n++;
Parameter
Passing by
Reference
Structured Try
If x = 0 Then
Exception
Throw New Exception( _
Handling
"x equals zero")
Else
Throw New Exception( _
"x does not equal zero")
End If
Catch err As System.Exception
MsgBox( _
"Error: " & Err.Description)
Finally
MsgBox( _
"Executing finally block.")
End Try
- 17 -
finally
{
System.Console.WriteLine(
"executing finally
block");
}
o = Nothing
o = null;
Set an
Object
Reference
to Nothing
Initializing Dim dt as New System.DateTime( _ System.DateTime dt =
new System.DateTime(
Value Types 2001, 4, 12, 22, 16, 49, 844)
2001, 4, 12, 22, 16,
49, 844);
- 18 -
- 20 -
Types of validators
There are 6 types of validators
Required field validator ( for empty check).
Compare validator. We can compare
controls (like password n confirm password)
value (age must be greater then 18)
data type check (salary must be no.)
Range validator
Regular expression validator
Pre define format (valid email address)
- 21 -
Custom validator
Validation summary
Web.UI.Validation.js is the file name in which jscript of all these validator are
available.
We not able to associate controls with validators in ASP.Net 1.1 but can do this in
2.0 E.g. username n pass and search is check by different button.
- 22 -
Validation summary
To Make startup page (go to solution explorer right click on page set as start
page).
checkbox
checkbox1_checked changed event
{
If(checkbox.checked == true)
{
- 23 -
Textbox1.font.bold = true;
}
Else
{
Textbox1.font.bold = false;
}
}
o web server control has property
autoPostBack to make the page submit when there value changes
coz all web server control accept value after clicking
on button.
Radio button
o Property GroupName to mention the group.
o They have only selected whenever we click on them not lick checkbox.
radiobutton_checked changed event
{
Textbox1.forecolor = color.red
}
o We must include a namespace to use color
Using System.Drawing;
Checkbox list
o DataBound control it is collection of checkboxes
o Useful when we want to make checkboxes at runtime.
o Properties
Repeat columns value
Repeat direction vertical/ horizontal
o 3 method of defining the checkboxes
Edit items
Selected by default selected
Enabled disable to user to change it
Run time data entry
Page_load
{
If(page.isPostBack == false)
- 24 -
{
Checkboxlist1.itms.add(abc);
Checkboxlist1.itms.add(xyz);
}
/* For collection
We must have namespace
Using System.collection;
Collection is data structure to store items
Arraylist
array of objects which increase its size dynamically.
by default has size equal to 6 characters.
*/
Arraylist arr = new ArrayList();
arr.add(abc);
arr.add(xyz);
checkboxlist1.dataSource = arr;
checkboxlist1.dataBind();
// both these methods work together
Checkboxlist1.items[0].enabled = false;
}
Button1_click
{
For(int32 i=0;i<checkboxlist1.items.count; i++)
{
If(checkboxlist1.item[i].selected==true)
Textbox1.text+=checkboxlist1.item[i].
text +\n;
}
}
- 25 -
Textbox property
Textmode multiple line (to display data in multiple line)
To store different value in checkbox at behind
(hidden name value, display name text)
To add value field
Checkboxlist1.items.add(new listItem(aa,1));
To retrieve value
Checkboxlist1.items[i].value;
DATABASE HANDLING
Difference between MsAccess and SQL
In oracle & SQL there are triggers, procedure, functions, cursor generally know as
compile objects which are store in database and executed in database only due to
which traffic will not slow down.
Database server and application server are two different things.
Store procedure once executed, next time the procedure will be faster than before.
Less space in access.
Less security in access.
Oracle is 99.9% used by the those companies which have own server.
In Web development 99% we use SQL.
- 26 -
Database connectivity
To create database
o View server explorer
o In last there is server to know the server name
o Data connection(right click) create new SQL server DB
o Mention these fields
Server name sac
Use SQL server authentication
Username sa (default)
New database name dbemployee
o Now this dbemployee will be added in data connection
o Sac.dbemployee table(right click) add new table
o Mention column name and data type as
Eno
int
Ename varchar(50)
- 27 -
Eaddress varchar(50)
Esal
int
Difference between varchar and nvarchar is that varchar uses ASCII and nvarchar
uses Unicode.
Web.config file
o It is used to store connection string. It is to manipulate it if server name, uid
changes instead of going to each n every page we just change it in web.config.
o Non compile file where as module has to compile
o XML based, Case sensitive
o Secure in version 2.0 (we cant view the file without coding)
o Intelligence help is provided in version 2.0
o It can be multiple in single project but machine.config is single in one project.
o It is for project configuration e.g. security setting, session setting etc
o To add web.config
Website add new item web conf file
o Add connection string in this file
<connection string>
<add name=nonu connectionString=server=sac; database=dbemployee;
key
uid=sa; pwd=admin/>
It is used if u have
mentioned password
</connection string>
o Server name in connection string is not compulsory if ur server is same
system where application is running.
o In 1.0 we add connection string in <appsettings> tag
Eg. <add key=cs value=database=dbemp;uid=sa>
And Excess this as configurationSetting.AppSettings[cs]
Difference between
o Hash stores key as well as value
o Array stores only value
We should add
Using System.data.SQLClient;
Class_default
{
SQLConnection con = new SQLConnection();
// SQLConnection class is used to establish connection
Page_load
- 28 -
{
This.smartNavigation = true;
// in c# we use this and in VB.Net we use me
Con.connectionString =
ConfigurationManager.ConnectionString[nonu].
connectionString;
// ConfigurationManager is used to read connection string.
If (con.State ==ConnectionState.Closed)
{
Con.open();
}
// open() make connection active & make connectivity with SQL server.
// before using open() we must check the state of connection otherwise
problem of connection pooling occur.
// run this much if it page opens that means connectivity is ok
// dont insert control directly on page coz it will not look going when the resolution
changes.
If(page.isPostBack == false)
textbox1.text=getAuto().toString();
}
Button1_click // save
{
SQLcommand cmd = new sqlcommand();
// SQLCommand bridge between data and database. Used for save, delete, update,
display
cmd.CommandText.=Insert into themp
values(@eno,@en,@ed@es);
// commandText is used to specify query or store procedure, @eno are parameters with
are used at runtime
cmd.command=con;
// connection established
cmd.parameters.add(@eno,sqldbtype.Int).value =
convert.ToInt32(textbox1.text);
- 29 -
convert.ToInt32(textbox1.text);
cmd.parameters.add(@en,sqldbtype.Varchar, 50).
value =textbox2.text;
cmd.executeNonQuery();
cmd.dispose();
textbox1.text
textbox2.text
textbox3.text
textbox4.text
=
=
=
=
;
;
;
;
}
Display code
Button4_click
{
SQLcommand cmd = new sqlcommand();
cmd.commandText =select * from tbemp;
cmd.connection = con;
SQLDataReader dr;
/*
*/
Dr = cmd.ExecuteReader ();
// ExecuteReader just execute the query n store the data in variable(just for display)
Listbox1.dataTextField =ename;
// DataTextField display the data in listbox
Listbox1.dataValueField =empno;
// value at the back side of listbox (not visible)
- 31 -
Listbox1.DataSource = dr;
Listbox1.DataBind();
Dr.close();
cmd.dispose();
}
Listbox1_selectedIndexChanged
{
SQLcommand cmd = new sqlcommand ();
cmd.commandText=select * from dbemp where empno =
@eno;
cmd.command=con;
cmd.parameters.add (@eno, sqldbtype.Int).value =
convert.ToInt32 (listbox1.selectedValue);
cmd.parameters.add (@eno, sqldbtype.Int).value =
convert.ToInt32 (listbox1.selectedItem.text);
// selectedValue to get the value behind the data selected
// selectedItem.text to get the value display in the listbox
SqlDataReader dr;
Dr = cmd.ExecuteReader();
If(dr.HasRows)
{
Dr.Read();
// to read the next line
Textbox1.Text = dr [empno].ToString();
Textbox1.Text = dr [ename].ToString();
Textbox1.Text = dr [eaddress].ToString();
Textbox1.Text = dr [esal].ToString();
}
// convert the data to string coz by default they are objects
Dr.close();
cmd.dispose();
}
STORE PROCEDURES
- 33 -
Save procedure
CREATE PROCEDURE insemp
(
@eno int,
@en varchar(50),
@ed varchar(50),
@es int
)
AS
Insert into tbemp values(@eno,@en,@ed,@es)
When we save this CREATE will automatically changes to ALTER that means in
future we can only alter this procedure.
If we dont specify the size in varchar then it will store only one character.
Update procedure
CREATE PROCEDURE updemp
(
@eno int,
@en varchar(50),
@ed varchar(50),
@es int
)
- 34 -
AS
Update tbemp set ename = @en, eaddress = @ed, esal =
@es where empno = @eno
Delete procedure
CREATE PROCEDURE delemp
(
@eno int
)
AS
Delete tbemp where empno = @eno.
Display procedure
CREATE PROCEDURE dispemp
AS
Select * from tbemp.
Find procedure
CREATE PROCEDURE findemp
(
@eno int
)
AS
Select * from tbemp where empno = @eno
We can store more than one query in one procedure when we do more than one work
in a single step like when we click on button then Save n Update will run
simultaneous.
Authentication procedure
- 35 -
If @ap is null
Return -1
Else
If @ap = @p
Return 1
Else
Return -2
If we dont write anything in front of parameter then by default they are of type input.
If uname is not valid then select statement return null in @ap.
Now instead of writing command in front end we write these two lines
o Cmd.commandText=Procedure name;
o Cmd.commandType=commandType.StoreProcedure;
CommandType tells us the type of command.
To enter data directly to table right click on the table in the server explorer
show table data.
Add two three accounts in the table
Design the front view design of login screen
Using System.data.SQLClient;
Class_default
{
SQLConnection con = new SQLConnection;
Page_load
{
Con.connectionString = configurationManager.
connectionString[nonu].connectionSting;
if (con.state = = connectionState.closed)
{
Con.open();
}
}
Private Int32 checkuser(String u, String p)
{
SQLCommand cmd = new SQLCommand();
cmd.commandText = loginCheck;
cmd.commandType = commandType.StoreProcedure
cmd.pamameter.add(@u,SQLVbType.varchar, 50).value=u;
cmd.pamameter.add(@p,SQLVbType.varchar, 50).value=p;
// to receive the value return by procedure we must make a parameter
SQLParameter p1 = new SQLParameter(@ret,
- 36 -
SQLDbtype.Int);
P1.Direction = ParameterDirection.returnValue;
// returnValue is the 4th type of parameter
// output parameter can be multiple but we can use only one returnValue.
cmd.parameter.add(p1);
cmd.ExecuteNonQuery();
// value will be added in @ret
Int32 k =convert.Toint32(cmd.parameter[@ret].value);
cmd.dispose();
Return k;
}
button1_click
{
Int32 r = checkUser(Textbox1.text, Textbox2.text);
If ( r = = -1)
{
Label1.text = WRONG USER;
}
Else if ( r = = -2)
{
Label1.text = wrong Password;
}
Else
{
Label1.text = LOGIN;
}
}
// this is called connected approach coz in this we use open to connect
TEMPLATES
- 37 -
o Header template
o Footer template
o Select template
o Pager template
o Edit item template
o Separator template
o Alternating item template
o Insert item template
o Empty data template
Last two were added in version 2.0
All templates always use with composite databound control
Composite databound control are those in which we add child
Three type of Composite databound control in version 1.1
o Repeator
o Data list
o Data grid
Five type of Composite databound control are there in version 2.0
o Repeator
o Data list
o Grid view
o Form view
o Detail view
All Composite databound control work with templates & vice versa
Repeater
- 38 -
bookPub
varchar(50)
bookPrice int
bookImg
varchar(50) // we can also store this in binary
o Add two three records in the table.
o From the toolbox data add a repeater
o Add web.config file and make connectionString
using System.Data.SqlClient;
protected void Page_Load(object sender, EventArgs e)
{
repBind();
}
private void repBind()
{
SqlDataAdapter adp = new SqlDataAdapter("select * from
tbbook",ConfigurationManager.ConnectionStrings
["cs"].ConnectionString);
// SqlDataAdapter always used with disconnection approach. It implicit open & close the
Connection
DataSet ds = new DataSet();
/* DataSet
Collection of table
Equal to DataReader
We can set the relations
Very important point is that it read and write data in XML format
Types
o Type DataSet
We define the structure at design time
Performance is better than untype DataSet
We use it in reports or when we know fixed no. of columns
Extension .xsd
o Untype DataSet
Define structure at run time
Data is also added at run time
Performance is slow
We use this if we dont know fixed no of column
*/
adp.Fill(ds);
// Fill create connection, open it, execute query, put data in DataSet close connection
Repeater1.DataSource = ds;
Repeater1.DataBind();
- 39 -
Go to HTML of default.aspx
<td><%#Eval("bookId")%></td>
<td><%#Eval("bookTitle")%></td>
<td><%#Eval("bookAuthor")%></td>
<td><%#Eval("bookPub")%></td>
<td><%#Eval("bookPrice")%></td>
<td><%#CalDis(Convert.ToInt32(Eval("bookPrice"))) %>
</td>
<td><%#CalAmt(Convert.ToInt32(Eval("bookPrice"))) %>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
<AlternatingItemTemplate>
<tr bgcolor=olive>
<td><%#Eval("bookId")%></td>
<td><%#Eval("bookTitle")%></td>
<td><%#Eval("bookAuthor")%></td>
<td><%#Eval("bookPub")%></td>
<td><%#Eval("bookPrice")%></td>
<td><%#CalDis(Convert.ToInt32(Eval("bookPrice"))) %>
</td>
<td><%#CalAmt(Convert.ToInt32(Eval("bookPrice"))) %>
</td>
</tr>
</AlternatingItemTemplate>
</asp:Repeater>
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
RepBind();
}
private void RepBind()
{
SqlDataAdapter adp = new SqlDataAdapter("select * from bbook",
ConfigurationManager.ConnectionStrings["cs"].ConnectionString);
- 41 -
Template
Datalist
- 42 -
Using System.Data.Sqlclient;
Private void ListBind()
{
SqlDataAdapter adp = new SqlDataAdapter("select * from tbbook",
ConfigurationManager.ConnectionStrings["cs"].ConnectionString);
In HTML
<asp:DataList>
<ItemTemplate>
<b>Title:</b><%#Eval(bookTitle)%><br/>
<b>Author:</b><%#Eval(bookAuthor)%><br/>
<b>Publisher:</b><%#Eval(bookPub)%><br/>
<b>Price:</b><%#Eval(bookPrice)%><br/>
<asp:LinkButton ID=lb Text=Edit CommandName=Edit
Runat=server>
</asp:LinkButton>
</ItemTemplate>
</asp:DataList>
- 43 -
<EditItemTemplate>
<b>Title:</b>
<asp:TextBox ID=t1 Text=<%#Eval(bookTitle)%>
Runat=server>
</asp:TextBox><br/>
<b>Author:</b>
<asp:TextBox ID=t1 Text=<%#Eval(bookTitle)%>
Runat=server>
</asp:TextBox><br/>
<b>Publisher:</b>
<asp:TextBox ID=t1 Text=<%#Eval(bookPub)%>
Runat=server>
</asp:TextBox><br/>
<b>Price:</b>
<asp:TextBox ID=t1 Text=<%#Eval(bookPrice)%>
Runat=server>
</asp:TextBox><br/>
<asp:LinkButton ID=lb Text=Update
CommandName=Update Runat=server>
</asp:LinkButton>
<asp:LinkButton ID=lb Text=Cancel
CommandName=Cancel Runat=server>
</asp:LinkButton>
</EditItemTemplate>
To make event
DataList properties icon(event) EditCommand(double click)
DataList properties icon(event) CancelCommand(double click)
DataList1_EditCommand(source, e)
{
DataList1.EditItemIndex = e.Item.ItemIndex;
{
DataList1.EditItemIndex = -1;
ListBind();
}
DataList1_UpdateCommand(source, e)
{
String title, author, pub;
Int32 prc;
Title=((textbox)(e.Item.FindControl(t1))).text;
Author =((textbox)(e.Item.FindControl(t2))).text;
Pub =((textbox)(e.Item.FindControl(t3))).text;
Prc=Convert.ToInt32(((textbox)
(e.Item.FindControl(t4))).text);
bid = Convert.ToInt32
(DataList1.DataKeys[e.Item.ItemIndex]);
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.
ConnectionStrings["cs"].ConnectionString;
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "update tbbook set bookTitle=@title,
bookAuthor =@author,
bookPub=@pub, bookPrice=@prc where
bookId=@bid";
cmd.Connection = con;
cmd.Parameters.Add("title", SqlDbType.VarChar, 50).Value = title;
cmd.Parameters.Add("author", SqlDbType.VarChar, 50).Value=author;
cmd.Parameters.Add("pub", SqlDbType.VarChar, 50).Value = pub;
- 45 -
}
To make direct connection with database without coding we use SqlDataSource
<ItemTemplate>
<b>Name:</b><%#Eval("productName")%><br />
<b>Price:</b><%#Eval("unitPrice")%><br />
<b>CategoryId:</b><%#Eval("categoryId")%><br />
<b>SupplierId:</b><%#Eval("supplierId")%><br />
<asp:LinkButton ID="lb" Text=Edit CommandName="edit"
runat=server>
</asp:LinkButton><br /><br />
</ItemTemplate>
<EditItemTemplate>
<b>Name:</b><asp:TextBox ID="tb1" Text='<%#Eval
("productName")%>' runat=server></asp:TextBox><br />
<b>Price:</b><asp:TextBox ID="tb2" Text='<%#Eval
("unitPrice")%>' runat=server></asp:TextBox><br />
<b>Category:</b>
<asp:DropDownList ID="dd1" DataTextField="categoryName"
DataValueField="CategoryId" DataSourceID="SqlDataSource2"
runat=server SelectedValue='<%#Eval("categoryId")%>'>
</asp:DropDownList><br />
<b>Supplier:</b>
<asp:DropDownList ID="dd2" DataTextField="companyName"
DataValueField="supplierId" DataSourceID="SqlDataSource3"
runat=server SelectedValue='<%#Eval("supplierId")%>'>
</asp:DropDownList><br />
- 46 -
DataList1_EditCommand(source, e)
{
DataList1.EditItemIndex = e.Item.ItemIndex;
DataList1.DataBind();
}
DataList1_CancelCommand(source, e)
{
DataList1.EditItemIndex = -1;
DataList1.DataBind();
}
DataList1_UpdateCommand(source, e)
{
String pn, prc, cd, sd, pid;
pn = ((TextBox)(e.Item.FindControl("t1"))).Text;
prc =((TextBox)(e.Item.FindControl("t2"))).Text;
cd = ((DropDownList)(e.Item.FindControl("dd1"))).Text;
sd ((DropDownList)(e.Item.FindControl("dd2"))).Text);
SqlDataSource1.UpdateParameter[pn].DefaultValue=pn;
SqlDataSource1.UpdateParameter[un].DefaultValue=pn;
SqlDataSource1.UpdateParameter[cid].DefaultValue=cd;
SqlDataSource1.UpdateParameter[sid].DefaultValue=sd;
/*
- 47 -
*/
pd = (DataList1.DataKeys[e.item.itemIndex]).ToString();
SqlDataSource1.UpdateParameter[pid].DefaultValue=pd;
SqlDataSource1.update();
Datalist1.EditItemIndex = -1;
Datalist1.databind();
}
- 48 -
Using System.Data.Sqlclient;
Page_load
{
If(page.isPostBack==false)
{
SqlDataAdapter adp = new SqlDataAdapter("select * from tbbook",
ConfigurationManager.ConnectionStrings["cs"].ConnectionString);
}
}
Button_click
{
String st=;
For(int32 i=0; i<DataList.item.count;i++;)
{
checkbox c=(checkbox)(Datalist1.item[I].FindControl(cb));
if(c.checked ==true)
st +=DataList1.DataKey[I].toString() +,;
}
St = st.Substring(0,st.length-1);
SqlDataAdapter adp = new SqlDataAdapter("select * from products
where product In(+st+)),ConfigurationManager.
ConnectionStrings["cs"].ConnectionString);
In HTML
<asp:DataList1>
<ItemTemplate>
<b><%Eval(productName)%><br/>
<asp:checkbox ID=cb text=Buy runat=server>
- 49 -
</ItemTemplate>
</asp:DataList1>
<asp:DataList2>
<ItemTemplate>
<b><%Eval(productName)%></b><br/>
<b><%Eval(unitPrice)%></b><br/>
</ItemTemplate>
</asp:DataList1>
- 50 -
Using System.Data.Sqlclient;
Private void ListBind()
{
SqlDataAdapter adp = new SqlDataAdapter("select * from tbbook",
ConfigurationManager.ConnectionStrings["cs"].ConnectionString);
- 51 -
DataRowView r;
// DataRowView class only accept single row.
r=ds.Tables[0].DefaultView[0];
TextBox1.Text
TextBox2.Text
TextBox3.Text
TextBox4.Text
= r[0]["bookTitle"].ToString();
=r[0]["bookAuthor"].ToString();
= r[0]["bookPub"].ToString();
= r[0]["bookPrice"].ToString();
In HTML
<asp:DataList>
<ItemTemplate>
<b>Title:
</b><asp:LinkButton ID="lb" Text='<%#Eval("bookTitle")%>'
CommandName=select" runat=server>
</asp:LinkButton><br />
<b>Author: </b><%#Eval("bookAuthor")%><br />
<b>Publisher: </b><%#Eval("bookPub")%><br />
<b>Price: </b><%#Eval("bookPrice")%><br />
</ItemTemplate>
- 52 -
In HTML
<head runat="server">
<title>Untitled Page</title>
<style >
.abc{font-size:larger;font-weight:bold}
.xyz{display:none;visibility:hidden}
</style>
<script language='javascript'>
function getData(id)
{
var e;
color(id);
e=document.getElementById('d'+id);
if(e)
{
if(e.style.display!='block')
{
e.style.display='block';
e.style.visibility='visible';
}
else
{
e.style.display='none';
e.style.visibility='hidden';
}
}
for(var i=0;i<6;i++)
{
if(i==id)
{
i++;
}
var e1=document.getElementById('d'+i);
if(e1)
{
e1.style.display='none';
e1.style.visibility='hidden';
}
- 53 -
}
}
function color(id)
{
var e1;
e1=document.getElementById('h'+id);
if(e1)
{
e1.style.color='blue';
}
for(var i=0;i<6;i++)
{
if(i==id)
{
i++;
}
e2=document.getElementById('h'+i);
if(e2)
{
e2.style.color='black';
}
}
}
</script>
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div id='h<%#DataBinder.Eval(Container,"itemindex")%>' ondblclick=
'getData(<%#DataBinder.Eval(Container,"itemindex")%>)'
class='abc' onclick='color(<%#DataBinder.Eval
(Container,"itemindex")%>)' >
<b><%#Eval("bookTitle")%><br /></b>
</div>
<div id='d<%#DataBinder.Eval(Container,"itemindex")%>'
class='xyz'>
<b> Author:</b><%#Eval("bookAuthor")%><br />
<b> Publisher:</b><%#Eval("bookPub")%><br />
<b> Price:</b><%#Eval("bookPrice")%><br /><br />
</div>
</ItemTemplate>
</asp:Repeater>
- 54 -
Q. PAGING
Default.aspx.cs
protected void Page_Load(sender, e)
{
if (Page.IsPostBack == false)
{
PageBind(1);
}
}
private void PageBind(Int32 pg)
{
Int32 nor, repcol;
nor = (Convert.ToInt32(DropDownList1.SelectedValue));
if (nor <= 4)
{
repcol = nor;
}
else
{
repcol = Convert.ToInt32(nor / 2);
}
DataList1.RepeatColumns = repcol;
SqlConnection con = new SqlConnection();
con.ConnectionString=ConfigurationManager.
ConnectionStrings["cs"].ConnectionString;
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "paging";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@pagenumber",SqlDbType.Int).Value=pg;
cmd.Parameters.Add("@pagesize", SqlDbType.Int).Value = nor;
- 56 -
cmd.Connection = con;
SqlDataReader dr;
dr = cmd.ExecuteReader();
dr.Read();
Int32 total,t;
total = Convert.ToInt32(dr[0]);
if (total % nor == 0)
{
t = Convert.ToInt32(total / nor);
}
else
{
t = Convert.ToInt32(total / nor +1);
}
Label1.Text = pg.ToString();
Label2.Text = "of";
Label3.Text = t.ToString();
Int32 i;
ArrayList arr = new ArrayList();
arr.Add("<");
for (i = 1; i <= Convert.ToInt32(Label3.Text); i++)
{
arr.Add(i.ToString());
}
arr.Add(">");
DataList2.RepeatDirection=RepeatDirection.Horizontal;
DataList2.DataSource = arr;
DataList2.DataBind();
if (dr.NextResult())
{
DataList1.DataSource = dr;
DataList1.DataBind();
}
dr.Close();
cmd.Dispose();
Button1.Enabled
Button2.Enabled
Button3.Enabled
Button4.Enabled
if (pg == 1)
- 57 -
=
=
=
=
true;
true;
true;
true;
{
Button1.Enabled = false;
Button2.Enabled = false;
}
if (pg == Convert.ToInt32(Label3.Text))
{
Button3.Enabled = false;
Button4.Enabled = false;
}
}
DropDownList1_SelectedIndexChanged(sender, e)
{
PageBind(1);
}
protected void Button1_Click(sender, e) //First
{
PageBind(1);
}
protected void Button2_Click(sender, e) //previous
{
PageBind(Convert.ToInt32(Label1.Text) - 1);
}
protected void Button3_Click(sender, e) //Next
{
PageBind(Convert.ToInt32(Label1.Text) + 1);
}
protected void Button4_Click(sender, e) //Last
{
PageBind(Convert.ToInt32(Label3.Text));
}
void DataList2_SelectedIndexChanged(sender,e)
{
if (DataList2.SelectedIndex==0)
{
if ((Convert.ToInt32(Label1.Text))!= 1)
{
PageBind(Convert.ToInt32(Label1.Text) - 1);
}
}
else if(DataList2.SelectedIndex==DataList2.Items.Count-1))
if((Convert.ToInt32(Label1.Text))!=(DataList2.Items.Count - 2))
{
PageBind(Convert.ToInt32(Label1.Text) + 1);
}
}
- 58 -
else
{
PageBind(DataList2.SelectedIndex);
}
}
}
In HTML
<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
<b> Name:
</b><%#Eval("productName")%><br />
<b> Price:
</b><%#Eval("unitPrice")%><br />
<b> Category:</b><%#Eval("categoryName") %><br />
</ItemTemplate>
</asp:DataList>
<asp:DataList ID="DataList2" runat="server">
<ItemTemplate>
<asp:LinkButton ID="lb" Text='<%#Container.DataItem%>'
CommandName="select" runat="server">
</asp:LinkButton>
</ItemTemplate>
</asp:DataList>
- 59 -
GRIDVIEW
- 60 -
- 61 -
con.ConnectionString = ConfigurationManager.
ConnectionStrings["cs"].ConnectionString;
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText ="update tbbook set bookTitle=@title,bookAuthor=
@author, bookPub=@pub, bookPrice=@price where bookId=@id";
cmd.Connection = con;
cmd.Parameters.Add("@id",SqlDbType.Int).Value= Convert.ToInt32
(((Label)(GridView1.Rows[e.RowIndex].FindControl("l"))).Text);
cmd.Parameters.Add("@title", SqlDbType.VarChar, 50).Value =
((TextBox)(GridView1.Rows[e.RowIndex].FindControl("tb1"))).Text;
cmd.Parameters.Add("@author", SqlDbType.VarChar, 50).Value =
((TextBox)(GridView1.Rows[e.RowIndex].FindControl("tb2"))).Text;
cmd.Parameters.Add("@pub", SqlDbType.VarChar, 50).Value =
((TextBox)(GridView1.Rows[e.RowIndex].FindControl("tb3"))).Text;
cmd.Parameters.Add("@price",SqlDbType.Int).Value=Convert.ToInt32
(((TextBox)(GridView1.Rows[e.RowIndex].FindControl("tb4"))).Text);
cmd.ExecuteNonQuery();
cmd.Dispose();
GridView1.EditIndex = -1;
GrdBind();
}
GridView1_RowDeleting(sender, e)
{
Int32 eno;
// add DataKeyName in GridView Property
eno = Convert.ToInt32(GridView1.DataKeys
[e.RowIndex][0]);
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.
ConnectionStrings["cs"].ConnectionString;
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText="delete from tbbook where bookId=@id";
cmd.Connection = con;
cmd.Parameters.Add("@id",SqlDbType.Int).Value= eno;
cmd.ExecuteNonQuery();
cmd.Dispose();
GridView1.EditIndex = -1;
GrdBind();
}
- 62 -
In HTML
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField HeaderText="bookId">
<ItemTemplate>
<%#Eval("bookId")%>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="l"
Text='<%#Eval("bookId")%>'runat="server">
</asp:Label>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%#Eval("bookTitle")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tb1"
Text='<%#Eval("bookTitle")%>' runat="server">
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Author">
<ItemTemplate>
<%#Eval("bookAuthor")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tb2" Text='<%#Eval("bookAuthor")%>'
runat="server">
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Publisher">
<ItemTemplate>
<%#Eval("bookPub")%>
</ItemTemplate>
<EditItemTemplate>
- 63 -
- 64 -
Place Gridview.
Add Web Config file.
Gridview property AutoGenerateColumn false.
GridviewpropertyColumnsAdd(TemplateField)HeaderText Category
GridviewpropertyColumnsAdd(TemplateField)HeaderText Products
In HTML
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" Height="238px" Width="269px">
<Columns>
<asp:TemplateField HeaderText="Category">
<ItemTemplate>
<b>ID:</b><%#Eval("categoryId")%><br />
<b>Name:</b> <%#Eval("categoryName")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Products">
<ItemTemplate>
<asp:GridView ID="gv1" AutoGenerateColumns="false"
Width="500px" runat="server" DataSource='<%#GetData
(Convert.ToInt32(Eval("categoryId")))%>'>
<Columns>
<asp:BoundField HeaderText="ID"
DataField="productId" />
<asp:BoundField HeaderText="Name"
DataField="productName" />
<asp:BoundField HeaderText="Price"
DataField="unitPrice" />
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
- 65 -
</asp:GridView>
In this query will execute many time and this will lead to poor performance
Another way
public partial class _Default : System.Web.UI.Page
{
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
GrdBind();
}
- 66 -
adp.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
public DataView GetData(Int32 cid)
{
DataView dv = ds.Tables[1].DefaultView;
// DataView is used to store, filter, Navigate data. It is temperory file on client side.
dv.RowFilter = "categoryId=" + cid.ToString();
return dv;
}
}
- 67 -
r[1] = pc;
r[2] = -1;
ds.Tables[0].Rows.InsertAt(r, i);
i++;
}
i++;
}
DataRow r1;
r1 = ds.Tables[0].Rows[i];
r1[1] = "G.Total";
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(sender, e)
{
//Event in gridview which is called for all the rows for all templates.
if (e.Row.Cells[0].Text == "Sub Total")
{
e.Row.BackColor = Color.Gray;
}
if (e.Row.Cells[0].Text == "G.Total")
{
e.Row.BackColor = Color.Chocolate;
}
if (e.Row.Cells[1].Text == "-1")
{
e.Row.BackColor = Color.Pink;
e.Row.Cells[0].ColumnSpan = 3;
e.Row.Cells[0].Font.Bold = true;
e.Row.Cells[0].HorizontalAlign =
HorizontalAlign.Center;
e.Row.Cells.RemoveAt(2);
e.Row.Cells.RemoveAt(1);
}
if (e.Row.Cells[0].Text == "Name")
{
e.Row.BackColor = Color.Chocolate;
}
}
}
- 69 -
QUERY ANALYZER
select isnull (categoryname,'G.Toatal'),isnull (productname,'Sub Total'), sum(unitprice)
unitprice,sum(unitsinstock) unitsinstock from products a, categories b where
a.categoryId=b.categoryId group by categoryname, productname with rollup
// Select me wohi column name aayege jo group by me define hote hai
// rollup is always use with group by
// This query will replace all null with Sub Total it not check where it is end of category
or null in product name column that y we use second query.
************************************************************************
select case when(grouping(categoryname)=1) then 'G.Total' else categoryname end
categoryname,case when(grouping(productname)=1) then 'Sub Total' else productname
end productname, sum(unitprice) unitprice,sum(unitsinstock) unitsinstock from products,
sum(unitprice) unitprice,sum(unitsinstock) unitsinstock from products a, categories b
where a.categoryId=b.categoryId group by categoryname, productname with rollup
a, categories b where a.categoryId=b.categoryId group by categoryname, productname
with rollup
- 70 -
Place Gridview
Add Web config file n make connection string
Gridview properties autoGenrateColumns false
Click on the tasks menu of gridview Edit Template
Click on Empno in display and in its Template add what so ever control u want
then click on added data bindings and write code in code expression (like
Eval(empno))
Do same for other coloums.
When we mention command name of our choice then that is come under
RowCommand event
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GrdBind();
}
}
private void GrdBind()
{
if (e.CommandName == Save)
{
Int32 eno, es;
String en, eadd;
eno= Convert.ToInt32(((Label)
(GridView1.FooterRow.FindControl("label3"))).Text);
es= Convert.ToInt32(((TextBox)
(GridView1.FooterRow.FindControl("textbox6"))).Text);
en = ((TextBox)
(GridView1.FooterRow.FindControl("textbox2"))).Text;
eadd = ((TextBox)
(GridView1.FooterRow.FindControl("textbox4"))).Text;
if (con.State == ConnectionState.Closed)
{
con.ConnectionString = ConfigurationManager.
ConnectionStrings["cs"].ConnectionString;
con.Open();
}
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into tbemp
values(@eno,@en,@eadd,@es)";
cmd.Connection = con;
cmd.Parameters.Add("@eno", SqlDbType.Int).Value=eno;
cmd.Parameters.Add("@en", SqlDbType.VarChar,50).Value=en;
cmd.Parameters.Add("@eadd", SqlDbType.VarChar, 50).Value=eadd;
cmd.Parameters.Add("@es", SqlDbType.Int).Value = es;
cmd.ExecuteNonQuery();
// we can also use adp.insertCommand = cmd
cmd.Dispose();
GrdBind();
}
}
public Int32 AutoGen()
{
SqlCommand cmd = new SqlCommand();
if (con.State==ConnectionState.Closed)
{
con.ConnectionString = ConfigurationManager.
ConnectionStrings["cs"].ConnectionString;
con.Open();
}
cmd.Connection = con;
Int32 r = Convert.ToInt32(cmd.ExecuteScalar())+ 1;
- 72 -
cmd.Dispose();
return r;
}
protected void GridView1_RowEditing(sender,e)
{
GridView1.EditIndex = e.NewEditIndex;
GrdBind();
}
protected void GridView1_RowDeleting(sender, e)
{
Int32 eno;
// add DataKeyName in GridView Property
eno = Convert.ToInt32(GridView1.DataKeys
[e.RowIndex][0]);
if (con.State == ConnectionState.Closed)
{
con.ConnectionString = ConfigurationManager.
ConnectionStrings["cs"].ConnectionString;
con.Open();
}
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "delete from tbemp where empno=@eno";
cmd.Connection = con;
cmd.Parameters.Add("@eno", SqlDbType.Int).Value=eno;
cmd.ExecuteNonQuery();
cmd.Dispose();
GrdBind();
}
protected void GridView1_RowUpdating(sender, e)
{
Int32 eno, es;
String en, eadd;
eno = Convert.ToInt32(((Label)(GridView1.Rows[e.RowIndex].
FindControl("label2"))).Text);
es = Convert.ToInt32(((TextBox) (GridView1.Rows[e.RowIndex].
FindControl("textbox5"))).Text);
en = ((TextBox)(GridView1.Rows
[e.RowIndex].FindControl("textbox1"))).Text;
eadd = ((TextBox)(GridView1.Rows[e.RowIndex].
FindControl("textbox3"))).Text;
if (con.State == ConnectionState.Closed)
{
con.ConnectionString = ConfigurationManager.
- 73 -
ConnectionStrings["cs"].ConnectionString;
con.Open();
}
SqlCommand cmd = new SqlCommand();
cmd.ExecuteNonQuery();
cmd.Dispose();
GridView1.EditIndex = -1;
GrdBind();
}
protected void GridView1_RowCancelingEdit(sender, e)
{
GridView1.EditIndex = -1;
GrdBind();
}
}
- 74 -
LinkButton lk = (LinkButton)(e.Row.Cells[6].Controls[0]);
e.Row.Attributes["onClick"] = ClientScript.
GetPostBackClientHyperlink(lk, "");
}
}
protected void GridView1_SelectedIndexChanged(sender,e)
{
TextBox1.Text = GridView1.SelectedRow.Cells[0].Text;
TextBox2.Text = GridView1.SelectedRow.Cells[1].Text;
TextBox3.Text = GridView1.SelectedRow.Cells[2].Text;
TextBox4.Text = GridView1.SelectedRow.Cells[3].Text;
TextBox5.Text = GridView1.SelectedRow.Cells[4].Text;
}
In HTML
- 75 -
Place Gridview
Add web config file
Place CheckBox list
Place button
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.
ConnectionStrings["cs"].ConnectionString;
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from tbbook";
cmd.Connection = con;
SqlDataReader dr = cmd.ExecuteReader();
Int32 i;
for (i = 0; i < dr.FieldCount; i++)
{
CheckBoxList1.Items.Add(dr.GetName(i).ToString());
{
if (CheckBoxList1.Items[i].Selected == true)
{
st += CheckBoxList1.Items[i].Text + ",";
}
}
st = st.Substring(0, st.Length - 1);
String st1 = "select " + st + " from tbbook";
SqlDataAdapter adp=new SqlDataAdapter(st1,Configuration
Manager.ConnectionStrings["cs"].ConnectionString);
- 77 -
DETAILVIEW
Similar to GridView
we can display only single record
In built paging
Auto editing, delete, insert
We display fields in rows but in gridview we display fields in columns
In this there is AutoGenrateRow
Command name
o Edit
o Update
o Cancel
o Delete
o New
o Insert
We use Detail view for single record operation .
Place DetailView, SqlDataSource and configure them
Properties of DetailView
o AutoGenerateDeleteButton true
o AutoGenerateEditButton true
o AutoGenerateInsertButton true
o AllowPaging true
o DataKeyNames bookid
Properties of SqlDataSource
o UpdateQuery
update tbbook set bookTitle=@bookTitle, bookAuthor=@bookAuthor,
bookPub=@bookPub, bookPrice=@bookPrice where bookId=@bookId
o DeleteQuery
Delete from tbbook where bookId=@bookId
o InsertQuery
Insert into tbemp values(@empno,@ename,@eaddress,@esal)
- 78 -
DetailsView1_ItemUpdating(sender, e)
{
SqlDataSource1.UpdateParameters["eno"].DefaultValue =
e.Keys[0].ToString();
//Another way
//SqlDataSource1.UpdateParameters["eno"].DefaultValue=((TextBox)
(DetailsView1.Rows[0].Cells[1].Controls[0])).Text;
SqlDataSource1.UpdateParameters["en"].DefaultValue =
e.NewValues[1].ToString();
/* whenever we use update then two arrays are make one contaning old values other with
new values. In we refer to array with values as NewValues[ ]*/
SqlDataSource1.UpdateParameters["ed"].DefaultValue =
e.NewValues[2].ToString();
SqlDataSource1.UpdateParameters["es"].DefaultValue =
e.NewValues[3].ToString();
}
DetailsView1_ItemInserting(sender, e)
{
SqlDataSource1.InsertParameters["eno"].DefaultValue=((TextBox)
(DetailsView1.Rows[0].Cells[1].Controls[0])).Text;
SqlDataSource1.InsertParameters["en"].DefaultValue=((TextBox)
(DetailsView1.Rows[1].Cells[1].Controls[0])).Text;
SqlDataSource1.InsertParameters["ed"].DefaultValue=((TextBox)
(DetailsView1.Rows[2].Cells[1].Controls[0])).Text;
SqlDataSource1.InsertParameters["es"].DefaultValue=((TextBox)
(DetailsView1.Rows[3].Cells[1].Controls[0])).Text;
}
DetailsView1_ItemDeleting(sender, e)
{
SqlDataSource1.UpdateParameters["eno"].DefaultValue=
e.Keys[0].ToString();
}
- 79 -
Place DetailVeiw
Add Web Config File
DetailVeiw properties AutoGenrateRows false
DetailVeiw properties fields Add template fields
o Empno
o Name
o Address
o Salary
o For buttons
- 80 -
EditItemTemTextboxEditDataBinding codeEval(esal)
Update (CommandName update)
Cancel (CommandName Cancel)
InsertItemTextboxEditDataBinding codeEval(esal)
Save
(CommandName Insert)
Cancel (CommandName Cancel)
Empty Data Template //To show table if no data available
ItemTemp LinkButtons
Add Data to Table (CommandName new)
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DetailBind();
}
}
private void DetailBind()
{
SqlDataAdapter adp = new SqlDataAdapter("select * from tbemp",
ConfigurationManager.ConnectionStrings["cs"].ConnectionString);
- 81 -
}
else
{
DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
// for ItemTemplate
}
DetailBind();
}
en = ((TextBox)(DetailsView1.Rows[1].
FindControl("textbox3"))).Text;
ed = ((TextBox)(DetailsView1.Rows[2].
- 82 -
FindControl("textbox5"))).Text;
es = Convert.ToInt32(((TextBox)(DetailsView1.Rows[3].
FindControl("textbox7"))).Text);
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.
ConnectionStrings["cs"].ConnectionString;
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into tbemp
values(@eno,@en,@ed,@es)";
cmd.Connection = con;
cmd.Parameters.Add("@eno", SqlDbType.Int).Value = eno;
cmd.Parameters.Add("@es", SqlDbType.Int).Value = es;
cmd.Parameters.Add("@en",SqlDbType.VarChar, 50).Value=en;
cmd.Parameters.Add("@ed",SqlDbType.VarChar,50).Value= ed;
cmd.ExecuteNonQuery();
cmd.Dispose();
DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
DetailBind();
}
protected void DetailsView1_ItemUpdating(sender, e)
{
Int32 eno, es;
String en, ed;
eno = Convert.ToInt32(((Label)(DetailsView1.Rows[0].
FindControl("label2"))).Text);
en = ((TextBox)(DetailsView1.Rows[1].
FindControl("textbox2"))).Text;
ed = ((TextBox)(DetailsView1.Rows[2].
FindControl("textbox4"))).Text;
es = Convert.ToInt32(((TextBox)(DetailsView1.Rows[3].
FindControl("textbox6"))).Text);
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.
ConnectionStrings["cs"].ConnectionString;
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "update tbemp set ename=@en,
eaddress=@ed,esal=@es where empno=@eno";
- 83 -
cmd.Connection = con;
cmd.Parameters.Add("@eno",SqlDbType.Int).Value = eno;
cmd.Parameters.Add("@es",SqlDbType.Int).Value = es;
cmd.Parameters.Add("@en",SqlDbType.VarChar,50).Value=en;
cmd.Parameters.Add("@ed",SqlDbType.VarChar,50).Value=ed;
cmd.ExecuteNonQuery();
cmd.Dispose();
DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
DetailBind();
}
protected void DetailsView1_PageIndexChanging(sender, e)
{
DetailsView1.PageIndex = e.NewPageIndex;
DetailBind();
}
}
- 84 -
Operator =
Source Control
ControlId GridView
o Click on add button
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DropDownBind();
GrdBind();
}
}
private void DropDownBind()
{
this.SmartNavigation = true;
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.
ConnectionStrings["cs"].ConnectionString;
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select CategoryName,CategoryId from
- 85 -
Categories";
cmd.Connection = con;
SqlDataReader dr;
dr = cmd.ExecuteReader();
DropDownList1.DataTextField = "CategoryName";
DropDownList1.DataValueField = "CategoryId";
DropDownList1.DataSource = dr;
DropDownList1.DataBind();
dr.Close();
cmd.Dispose();
}
private void GrdBind()
{
- 86 -
cb.Checked = false;
}
}
protected void LinkButton2_Click(sender, e)
{
SqlConnection con1 = new SqlConnection();
con1.ConnectionString = ConfigurationManager.
ConnectionStrings["cs1"].ConnectionString;
con1.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con1;
for (Int32 i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox cb = (CheckBox)(GridView1.Rows[i].
FindControl("cb"));
if (cb.Checked == true)
{
String pn;
Int32 p;
pn =((Label)(GridView1.Rows[i].
FindControl("l1"))).Text;
p = Convert.ToInt32(((Label)(GridView1.
Rows[i].FindControl("l2"))).Text);
cmd.CommandText = "insert into tbpurc
values(@pn"+i+",@p"+i+")";
cmd.Parameters.Add("@pn"+i,
SqlDbType.VarChar, 50).Value = pn;
cmd.Parameters.Add("@p"+i,
SqlDbType.Int).Value = p;
cmd.ExecuteNonQuery();
}
}
cmd.Dispose();
}
protected void LinkButton1_Click1(sender, e)
{
GrdBind2();
}
private void GrdBind2()
{
SqlDataAdapter adp = new SqlDataAdapter("select case when(
grouping (ProductName)=1) then 'Total' else ProductName end
ProductName, sum(Price) Price from tbpurc group by ProductName
with rollup", ConfigurationManager.ConnectionStrings
["cs1"].ConnectionString);
- 87 -
con1.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con1;
cmd.CommandText = "delete from tbpurc";
cmd.ExecuteNonQuery();
cmd.Dispose();
}
}
}
In HTML
<style type="text/css">
.abc{font-size:larger;font-weight:bold}
.xyz{Display:none;visibility:hidden}
</style>
<script type="text/javascript">
function GetData(id)
{
var e;
color(id);
e=document.getElementById('d'+id);
if(e)
{
if(e.style.display!='block')
{
e.style.display='block';
e.style.visibility='visible';
}
else
{
e.style.display='none';
e.style.visibility='hidden';
- 88 -
}
}
for(var i=0;i<12;i++)
{
if(i==id)
{
i++;
}
var e1=document.getElementById('d'+i);
if(e1)
{
e1.style.display='none';
e1.style.visibility='hidden';
}
}
}
function color(id)
{
var e1;
e1=document.getElementById('h'+id);
if(e1)
{
e1.style.color='blue';
}
for(var i=0;i<12;i++)
{
if(i==id)
{
i++;
}
e2=document.getElementById('h'+i);
if(e2)
{
e2.style.color='black';
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div style="text-align: justify">
Select The Category:
<asp:DropDownList ID="DropDownList1" runat="server"
AutoPostBack="True" OnSelectedIndexChanged=
- 89 -
"DropDownList1_SelectedIndexChanged" >
</asp:DropDownList><br />
<asp:GridView ID="GridView1" runat="server" Width="693px"
AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="cb" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProductId">
<ItemTemplate>
<%#Eval("ProductId")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<div id='h<%#DataBinder.Eval(Container,"RowIndex")%>'
class='abc' ondblclick='GetData (<%#DataBinder.
Eval(Container,"RowIndex")%>);' onclick='color
(<%#DataBinder.Eval(Container,"RowIndex")%>);'>
<asp:Label ID="l1"
Text='<%#Eval("ProductName")%>'
runat="server">
</asp:Label>
</div>
<div id='d<%#DataBinder.Eval(Container,"RowIndex")%>'
class='xyz' ondblclick='GetData(<%#DataBinder.
Eval(Container,"RowIndex")%>);' onclick='color
(<%#DataBinder.Eval(Container,"RowIndex")%>);'>
<b>Supplier Name:</b><%#Eval("CompanyName")%><br />
<b>Supplier Address:</b><%#Eval("Address")%><br />
<b>City:</b> <%#Eval("city")%><br />
<b>Phone:</b> <%#Eval("phone")%><br />
<b>Quantity per unit:</b><%#Eval("QuantityPerUnit")%><br />
<b>Units on Order:</b><%#Eval("UnitsOnOrder")%><br />
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Unit Price">
<ItemTemplate>
- 90 -
- 91 -
FORMVIEW
- 92 -
Similar to DetailView
we can display only single record
In built paging
We display fields in rows
In this there is no AutoGenrate Row or columns
No Limitation, No Default Template
Command name
o Edit
o Update
o Cancel
o Delete
o New
o Insert
We use from view for single record operation .
No Field and columns Available
Fully customize view
It is just like form
Place FormVeiw, Add Web Config File
DetailVeiw Tasks Edit Templates ItemTemplate
o Write Empno, place LabelEditDataBinding codeEval(empno)
o Write Ename, place LabelEditDataBinding codeEval(ename)
o Write Eaddress, place LableEditDataBindincodeEval(ename)
o Write Esal, place LabelEditDataBinding codeEval(esal)
o Place LinkButtons
Edit (CommandName edit)
New (CommandName new)
Delete(CommandName delete)
EditItemTemplate
o Write Empno, place LabelEditDataBinding codeEval(empno)
o Write Ename, place TextboxEditDataBinding codeEval(ename)
o Write Eaddress, place TextboxEditDataBindincodeEval(ename)
o Write Esal, place TextboxEditDataBinding codeEval(esal)
o Place LinkButtons
Update (CommandName update)
Cancel (CommandName Cancel)
InsertItemTemplate
o Write Empno, place TextboxEditDataBinding codeEval(empno)
o Write Ename, place TextboxEditDataBinding codeEval(ename)
o Write Eaddress, place TextboxEditDataBindincodeEval(ename)
o Write Esal, place TextboxEditDataBinding codeEval(esal)
o Place LinkButtons
Save
(CommandName Insert)
Cancel (CommandName Cancel)
EmptyDataTemplate //To show table if no data available
o Write No Data Available
o Add LinkButtons
Add Data to Table (CommandName new)
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
FrmBind();
}
}
private void FrmBind()
{
}
protected void FormView1_ModeChanging(sender, e)
{
if (e.NewMode == FormViewMode.Edit)
{
FormView1.ChangeMode(FormViewMode.Edit);
// for EditItemTemplate
}
else if (e.NewMode == FormViewMode.Insert)
{
FormView1.ChangeMode(FormViewMode.Insert);
// for InsertItemTemplate
}
else
{
FormView1.ChangeMode(FormViewMode.ReadOnly);
// for ItemTemplate
}
FormBind();
}
protected void FormView1_ItemDeleting(sender, e)
{
Int32 eno;
eno = Convert.ToInt32(((Label)(FormView1.
FindControl("label1"))).Text);
- 94 -
eno = Convert.ToInt32(((TextBox)(FormView1.
FindControl("textbox4"))).Text);
en= ((TextBox)(FormView1.FindControl("textbox5"))).Text;
ed= ((TextBox)(FormView1.FindControl("textbox6"))).Text;
es = Convert.ToInt32(((TextBox)(FormView1.
FindControl("textbox7"))).Text);
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.
ConnectionStrings["cs"].ConnectionString;
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into tbemp
values(@eno,@en,@ed,@es)";
cmd.Connection = con;
cmd.Parameters.Add("@eno", SqlDbType.Int).Value = eno;
cmd.Parameters.Add("@es", SqlDbType.Int).Value = es;
cmd.Parameters.Add("@en",SqlDbType.VarChar, 50).Value=en;
cmd.Parameters.Add("@ed",SqlDbType.VarChar,50).Value= ed;
cmd.ExecuteNonQuery();
cmd.Dispose();
FormView1.ChangeMode(FormViewMode.ReadOnly);
FormBind();
}
protected void FormView1_ItemUpdating(sender, e)
{
Int32 eno, es;
String en, ed;
eno = Convert.ToInt32(((Label)(FormView1.
FindControl("label2"))).Text);
en=((TextBox)(FormView1.FindControl("textbox1"))).Text;
ed=((TextBox)(FormView1.FindControl("textbox2"))).Text;
es = Convert.ToInt32(((TextBox)(FormView1.
FindControl("textbox3"))).Text);
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.
ConnectionStrings["cs"].ConnectionString;
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "update tbemp set ename=@en,
- 95 -
CLASSES
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Namespace nsEmp
Public Class clscomfuntion
Public Shared Sub Fill_Data(ByVal qry As String,
ByVal obj As ListControl,
ByVal datatext As String,
ByVal datavalue As String)
Dim adp As New SqlDataAdapter(qry,
"DataBase=dbemp;uid=sa")
Dim ds As New DataSet
- 96 -
adp.Fill(ds)
obj.DataTextField = datatext
obj.DataValueField = datavalue
obj.DataSource = ds
obj.DataBind()
End Sub
End Class
Public Class clsEmp
Public eno As Int32
Public en As String
Public eadd As String
Public es As Int32
we dont use public variable we use public properties coz they can be readonly,
writeonly, validation & checks, for security
Public Sub New()
Constructor
eno = 11
en = "Sachin"
eadd = "Ambala"
es = 23000
End Sub
Public Function disp() As String
Return "Empno: " & eno & "EName: " & en & "
Address: " & eadd & "Esal: " & es
End Function
End Class
Public Class clsEmp1
Private eno As Int32
Private en As String
Private eadd As String
Private es As String
Public Sub New()
eno = 11
en = "Gupta"
eadd = "Cantt"
es = "20000"
End Sub
Public Property p_empno() As Int32
Get
Return eno
End Get
Set(ByVal value As Int32)
eno = value
- 97 -
End Set
End Property
Public Property p_ename() As String
Get
Return en
End Get
Set(ByVal value As String)
en = value
End Set
End Property
Public Property p_eadd() As String
Get
Return eadd
End Get
Set(ByVal value As String)
eadd = value
End Set
End Property
- 98 -
End Property
End Class
End Namespace
Place textbox
Place three buttons
Place DropDownList
- 99 -
- 101 -
Inherits clsemp
Public Shadows shadow As Int32
Public Overrides Property p_sal() As Integer
Get
End Get
Set(ByVal value As Integer)
End Set
End Property
End Class
Public Class ConstructorOverloading
Public Sub New()
End Sub
Public Sub New(ByVal a As String)
End Sub
Public Sub New(ByVal a As String, ByVal b As Int32)
End Sub
Public Sub New(ByVal a As Int32)
End Sub
End Class
End Namespace
Imports System.Data.SqlClient
Imports System.Data
Imports System.Configuration
Namespace nsemp
Public Interface intcom
Sub Save_Rec()
Sub Update_Rec()
Sub Delete_Rec()
Function Find_rec() As DataSet
End Interface
Public Interface intemp
Property p_empno() As Int32
Property p_ename() As String
Property p_eadd() As String
- 102 -
End Sub
End Class
Public Class clsemp
Inherits clscon
Implements intcom, intemp
'phele class inherit then implement interface
Private
Private
Private
Private
eno As Int32
en As String
ed As String
es As Int32
- 103 -
Return ds
End Function
Public Sub Save_Rec() Implements intcom.Save_Rec
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim cmd As New SqlCommand("insemp", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("@eno", SqlDbType.Int).Value
= p_empno
cmd.Parameters.Add("@en", SqlDbType.VarChar, 50).
Value = p_ename
cmd.Parameters.Add("@ed", SqlDbType.VarChar, 50).
Value = p_eadd
cmd.Parameters.Add("@es", SqlDbType.Int).Value
= p_esal
cmd.ExecuteNonQuery()
cmd.Dispose()
con.Close()
End Sub
- 104 -
End Class
End Namespace
In Default.aspx.cs
Imports System.Data
Partial Class _Default
Inherits System.Web.UI.Page
Dim obj As New nsemp.clsemp
Protected Sub Page_Load() Handles Me.Load
End Sub
Protected Sub Button1_Click()
obj.p_empno = Convert.ToInt32(TextBox1.Text)
obj.p_ename = TextBox2.Text
obj.p_eadd = TextBox3.Text
obj.p_esal = TextBox4.Text
obj.Save_Rec()
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
End Sub
Protected Sub Button2_Click() Handles Button2.Click
obj.p_empno = Convert.ToInt32(TextBox1.Text)
obj.Delete_Rec()
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
End Sub
Protected Sub Button3_Click() Handles Button3.Click
obj.p_empno = Convert.ToInt32(TextBox1.Text)
obj.p_ename = TextBox2.Text
obj.p_eadd = TextBox3.Text
obj.p_esal = TextBox4.Text
obj.Update_Rec()
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
End Sub
Protected Sub Button4_Click() Handles Button4.Click
- 106 -
using System.Data.SqlClient;
namespace nsemp
{
public interface intcom
{
void Save_Rec();
void Update_Rec();
void Delete_Rec();
DataSet Find_rec();
}
public interface intemp
{
Int32 p_empno
{
get;
set;
}
- 107 -
Int32 p_sal
{
get;
set;
}
String p_ename
{
get;
set;
}
String p_eadd
{
get;
set;
}
}
public abstract class clscon
{
protected SqlConnection con = new SqlConnection();
public clscon()
{
con.ConnectionString = ConfigurationManager.
ConnectionStrings["cs"].ConnectionString;
}
}
public class clsemp : clscon, intcom, intemp
{
//we define interface after comma and to impliment them right click on it n click
implement interface
private Int32 eno, es;
private String en, ed;
#region intemp Members
public int p_empno
{
get
{
return eno;
}
set
{
eno = value;
}
}
- 108 -
- 109 -
- 110 -
cmd.Dispose();
con.Close();
}
public DataSet Find_rec()
{
SqlDataAdapter adp = new
SqlDataAdapter("findemp", con);
adp.SelectCommand.Parameters.Add("@eno",
SqlDbType.Int).Value = p_empno;
adp.SelectCommand.CommandType =
CommandType.StoredProcedure;
DataSet ds = new DataSet();
adp.Fill(ds);
return ds;
}
#endregion
}
public class clscomfunction
{
public static void fill_data(String qry,ListControl
obj,String datatext, String datavalue)
{
SqlDataAdapter adp = new SqlDataAdapter(qry,
ConfigurationManager.ConnectionStrings["cs"]
.ConnectionString);
obj.p_eadd = TextBox3.Text;
obj.p_sal = Convert.ToInt32(TextBox4.Text);
obj.Save_Rec();
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
}
protected void Button2_Click(sender, e)
{
obj.p_empno = Convert.ToInt32(TextBox1.Text);
obj.Delete_Rec();
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
}
protected void Button3_Click(sender, e)
{
obj.p_empno = Convert.ToInt32(TextBox1.Text);
obj.p_ename = TextBox2.Text;
obj.p_eadd = TextBox3.Text;
obj.p_sal = Convert.ToInt32(TextBox4.Text);
obj.Update_Rec();
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
}
protected void Button4_Click(object ,EventArgs e)
{
nsemp.clscomfunction.fill_data("select * from
tbemp", ListBox1, "ename", "empno");
}
protected void ListBox1_SelectedIndexChanged()
{
obj.p_empno =
Convert.ToInt32(ListBox1.SelectedIndex);
DataSet ds = new DataSet();
ds=obj.Find_rec();
DataRowView r;
r=ds.Tables[0].DefaultView[0];
TextBox1.Text = r[0].ToString();
TextBox2.Text = r[1].ToString();
TextBox3.Text = r[2].ToString();
TextBox4.Text = r[3].ToString();
}
- 112 -
using System.Data.SqlClient;
using System.Collections.Generic; // To create custom collection (array
of objects)
namespace nsemp
{
public interface intemp
{
Int32 p_empno
{
get;
set;
}
Int32 p_esal
{
get;
set;
}
String p_ename
- 113 -
{
get;
set;
}
String p_eadd
{
get;
set;
}
}
public class clsempprp:intemp
//right click to implement interface
{
private Int32 eno, es;
private String en, ed;
#region intemp Members
public int p_empno
{
get
{
return eno;
}
set
{
eno = value;
}
}
public int p_esal
{
get
{
return es;
}
set
{
es = value;
}
}
public string p_ename
{
get
{
return en;
- 114 -
}
set
{
en = value;
}
}
public string p_eadd
{
get
{
return ed;
}
set
{
ed = value;
}
}
#endregion
}
public abstract class clscon
{
protected SqlConnection con = new SqlConnection();
public clscon()
{
con.ConnectionString = ConfigurationManager.
ConnectionStrings["cs"].ConnectionString;
}
}
public class clsemp : clscon
{
public void save_rec(clsempprp p)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("insemp", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@eno", SqlDbType.Int).Value
= p.p_empno;
cmd.Parameters.Add("@en", SqlDbType.VarChar,
50).Value = p.p_ename;
- 115 -
cmd.Parameters.Add("@ed", SqlDbType.VarChar,
50).Value = p.p_eadd;
cmd.Parameters.Add("@es", SqlDbType.Int).Value
= p.p_esal;
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
}
public void update_rec(clsempprp p)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("updemp", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@eno", SqlDbType.Int).Value
= p.p_empno;
cmd.Parameters.Add("@en", SqlDbType.VarChar,
50).Value = p.p_ename;
cmd.Parameters.Add("@ed", SqlDbType.VarChar,
50).Value = p.p_eadd;
cmd.Parameters.Add("@es", SqlDbType.Int).Value
= p.p_esal;
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
}
public void delete_rec(clsempprp p)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("delemp", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@eno", SqlDbType.Int).Value
= p.p_empno;
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
}
public List<clsempprp> Dis_rec()
{
// List is a class which is used to create custom collection
if (con.State == ConnectionState.Closed)
{
- 116 -
con.Open();
}
SqlCommand cmd = new SqlCommand("dispemp",con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr;
dr = cmd.ExecuteReader();
List<clsempprp> obj = new List<clsempprp>();
while (dr.Read())
{
clsempprp k = new clsempprp();
k.p_empno = Convert.ToInt32(dr[0]);
k.p_ename = dr[1].ToString();
k.p_eadd = dr[2].ToString();
k.p_esal = Convert.ToInt32(dr[3]);
obj.Add(k);
}
dr.Close();
cmd.Dispose();
con.Close();
return obj;
}
public List<clsempprp> find_rec(Int32 eno)
{
if (con.State ==ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("findemp",con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@eno",SqlDbType.Int).Value
=eno;
SqlDataReader dr;
dr = cmd.ExecuteReader();
List<clsempprp> obj = new List<clsempprp>();
if(dr.HasRows)
{
dr.Read();
clsempprp k = new clsempprp();
k.p_empno = Convert.ToInt32(dr[0]);
k.p_ename = dr[1].ToString();
k.p_eadd = dr[2].ToString();
k.p_esal = Convert.ToInt32(dr[3]);
obj.Add(k);
}
dr.Close();
cmd.Dispose();
- 117 -
con.Close();
return obj;
}
}
}
- 118 -
Place formview
DataKeyNames p_empno
Choose Data source object data source1
Enable Paging true
Place object data source1
Used with 3 tier architecture
Stateless ( after doing its work distry the connection)
Bind with class
Click on configure data source of object data source1
Select clsemp
Select choose method Disp_Rec
Update choose method update_Rec
Insert choose method save_Rec
Delete choose method Delete_Rec
Place List box
Choose Data source object data source2
DataField ename
DataValueempno
Place object data source1 configure data source of object data source1
Select clsemp
Select choose method Disp_Rec
Place another formview
DataKeyNames p_empno
Choose Data source object data source
Enable Paging true
Place object data sourceconfigure data source of object data source
Select clsemp
Select choose method Find_Rec
Update choose method update_Rec
Insert choose method save_Rec
Delete choose method Delete_Rec
Click on next
Pass eno from control listbox1
- 119 -
Complied classes
Reusable
Scope in multiple projects
In process ( required where the application is running) whereas exe is out process
Part of COM (component object model)
It is a software architecture which is used to design a software component
Small in size as compare to exe
Faster as compare to exe
DLL of .net self described. (no need to register the DLL. Just copy & run it, CLR
know in which order it will run & how it work)
Also called as Assemblies
To create it
File New Project class Library
using System.Data.SqlClient;
using System.Collections.Generic; // To create custom collection (array
of objects)
namespace nsemp
{
public interface intemp
{
Int32 p_empno
{
get;
set;
}
Int32 p_esal
{
get;
set;
}
String p_ename
{
get;
set;
}
String p_eadd
{
get;
set;
}
}
public class clsempprp:intemp
//right click to implement interface
{
private Int32 eno, es;
private String en, ed;
#region intemp Members
public int p_empno
{
get
{
return eno;
}
set
{
eno = value;
}
}
- 120 -
- 121 -
}
}
public class clsemp : clscon
{
public void save_rec(clsempprp p)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("insemp", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@eno", SqlDbType.Int).Value
= p.p_empno;
cmd.Parameters.Add("@en", SqlDbType.VarChar,
50).Value = p.p_ename;
cmd.Parameters.Add("@ed", SqlDbType.VarChar,
50).Value = p.p_eadd;
cmd.Parameters.Add("@es", SqlDbType.Int).Value
= p.p_esal;
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
}
public void update_rec(clsempprp p)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("updemp", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@eno", SqlDbType.Int).Value
= p.p_empno;
cmd.Parameters.Add("@en", SqlDbType.VarChar,
50).Value = p.p_ename;
cmd.Parameters.Add("@ed", SqlDbType.VarChar,
50).Value = p.p_eadd;
cmd.Parameters.Add("@es", SqlDbType.Int).Value
= p.p_esal;
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
}
public void delete_rec(clsempprp p)
{
if (con.State == ConnectionState.Closed)
- 122 -
{
con.Open();
}
SqlCommand cmd = new SqlCommand("delemp", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@eno", SqlDbType.Int).Value
= p.p_empno;
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
}
public List<clsempprp> Dis_rec()
{
// List is a class which is used to create custom collection
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("dispemp",con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr;
dr = cmd.ExecuteReader();
List<clsempprp> obj = new List<clsempprp>();
while (dr.Read())
{
clsempprp k = new clsempprp();
k.p_empno = Convert.ToInt32(dr[0]);
k.p_ename = dr[1].ToString();
k.p_eadd = dr[2].ToString();
k.p_esal = Convert.ToInt32(dr[3]);
obj.Add(k);
}
dr.Close();
cmd.Dispose();
con.Close();
return obj;
}
public List<clsempprp> find_rec(Int32 eno)
{
if (con.State ==ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("findemp",con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@eno",SqlDbType.Int).Value
- 123 -
=eno;
SqlDataReader dr;
dr = cmd.ExecuteReader();
List<clsempprp> obj = new List<clsempprp>();
if(dr.HasRows)
{
dr.Read();
clsempprp k = new clsempprp();
k.p_empno = Convert.ToInt32(dr[0]);
k.p_ename = dr[1].ToString();
k.p_eadd = dr[2].ToString();
k.p_esal = Convert.ToInt32(dr[3]);
obj.Add(k);
}
dr.Close();
cmd.Dispose();
con.Close();
return obj;
}
}
}
using System.Collections.Generic;
public partial class _Default : System.Web.UI.Page
{
nsemp.clsempprp objprp = new nsemp.clsempprp();
nsemp.clsemp obj = new nsemp.clsemp();
protected void Page_Load(object sender, EventArgs e)
{
- 124 -
}
protected void Button1_Click(object sender,EventArgs e)
{
objprp.p_empno = Convert.ToInt32(TextBox1.Text);
objprp.p_esal = Convert.ToInt32(TextBox4.Text);
objprp.p_ename = TextBox2.Text;
objprp.p_eadd = TextBox1.Text;
obj.save_rec(objprp);
ListBox1.DataBind();
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
TextBox1.Focus();
}
protected void Button2_Click(object sender,EventArgs e)
{
objprp.p_empno = Convert.ToInt32(TextBox1.Text);
obj.delete_rec(objprp);
ListBox1.DataBind();
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
TextBox1.Focus();
}
protected void Button3_Click(object sender,EventArgs e)
{
objprp.p_empno = Convert.ToInt32(TextBox1.Text);
objprp.p_esal = Convert.ToInt32(TextBox4.Text);
objprp.p_ename = TextBox2.Text;
objprp.p_eadd = TextBox1.Text;
obj.update_rec(objprp);
ListBox1.DataBind();
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
TextBox1.Focus();
}
protected void Button4_Click(object sender,EventArgs e)
{
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
- 125 -
TextBox1.Focus();
}
protected void ListBox1_SelectedIndexChanged(object, e)
{
List<nsemp.clsempprp> k;
k = obj.find_rec(Convert.ToInt32(ListBox1.SelectedIndex));
TextBox1.Text
TextBox2.Text
TextBox3.Text
TextBox4.Text
=
=
=
=
k[0].p_empno.ToString();
k[0].p_ename;
k[0].p_eadd;
k[0].p_esal.ToString();
}
}
MASTER PAGES
- 126 -
XML file
<?xml version="1.0" encoding="utf-8" ?>
<Advertisements
xmlns="http://schemas.microsoft.com/AspNet/AdRotator
-Schedule-File">
<Ad xmlns="">
<ImageUrl xmlns="">a1.gif</ImageUrl>
<NavigateUrl xmlns="">default2.aspx</NavigateUrl>
<AlternateText xmlns="">First Add</AlternateText>
<Keyword xmlns="">Top</Keyword>
<Impressions xmlns="">1</Impressions>
// impressions is used to tell the ration of add to display
</Ad>
<Ad xmlns="">
<ImageUrl xmlns="">a2.gif</ImageUrl>
<NavigateUrl xmlns="">default3.aspx</NavigateUrl>
<AlternateText xmlns="">Second Add</AlternateText>
<Keyword xmlns="">Top</Keyword>
<Impressions xmlns="">2</Impressions>
</Ad>
<Ad xmlns="">
<ImageUrl xmlns="">a3.gif</ImageUrl>
<NavigateUrl xmlns="">default4.aspx</NavigateUrl>
<AlternateText xmlns="">Third Add</AlternateText>
<Keyword xmlns="">bottom</Keyword>
// Keyword is used to tell this add will display in which Adrotator if there is more than
one adrotator
<Impressions xmlns="">1</Impressions>
</Ad>
<Ad xmlns="">
<ImageUrl xmlns="">a4.gif</ImageUrl>
<NavigateUrl xmlns="">default5.aspx</NavigateUrl>
<AlternateText xmlns="">Fourth Add</AlternateText>
<Keyword xmlns="">bottom</Keyword>
<Impressions xmlns="">2</Impressions>
</Ad>
</Advertisements>
- 127 -
- 128 -
To Make a menu add menu toolbar from navigator and bind it with
SiteMapDataSource
Menu is a databound control we must use SiteMapDataSource to bind all type of
navigatot tools
SiteMapDataSource takes data from SiteMap file which is a XML file. No need to
bind it if there is only one SiteMap file
SiteMap File
SiteMapPath properties
Path separator >>>
Path Direction RootToCurrent/CurrentToRoot
PathLevelDisplayed -1 (to display full path)
RanderCurrentNoDeAsLink True
Menu Properties
StaticDisplayLevels 2
MaximumDynamicDisplayLevel 3
If there are more than one SiteMapFile then in web.config write
<system.web>
<siteMap enabled="true" defaultProvider="xy">
<providers>
<add name="xy" type="System.Web.XmlSiteMapProvider"
siteMapFile="Web.sitemap"/>
<add name="xz" type="System.Web.XmlSiteMapProvider"
siteMapFile="Web2.sitemap"/>
</providers>
</siteMap>
To bind navigator tool with second SiteMap, in SiteM apDataSource properties
Site MapProvider xz
- 129 -
st = st.Substring(i + 1);
// st = file name only
//create a upload folder on server to store uploades files
String fp = Server.MapPath("uploads");
// uploads path
fp = fp + "\\" + st;
FileUpload1.PostedFile.SaveAs(fp);
}
using System.Data.SqlClient;
using System.IO;
- 131 -
To retrieve it
- 132 -
To remove files
protected void Button3_Click(object sender, EventArgs e)
{
DirectoryInfo dir = new
- 133 -
DirectoryInfo(Server.MapPath("."));
//"." --> Current folder otherwise folder name
FileInfo fi = dir.GetFiles("*.gif);
foreach(FileInfo f in fi)
{
fi.Delete(f.FullName);
}
}
TEMPORARY TABLES
Place a GridView
{
DataTable item = new DataTable("tbitem");
//Datatable used to create temporary table
DataColumn c = new DataColumn("icode",
Type.GetType("System.Int32"));
c.AutoIncrement = true;
c.AutoIncrementSeed = 101;
c.AutoIncrementStep = 1;
item.Columns.Add(c);
c = new DataColumn("iname",
Type.GetType("System.String"));
c.AllowDBNull = false;
item.Columns.Add(c);
c = new DataColumn("irate",
Type.GetType("System.Int32"));
item.Columns.Add(c);
c = new DataColumn("iqty",
Type.GetType("System.Int32"));
item.Columns.Add(c);
c = new DataColumn("iamt",
Type.GetType("System.Int32"));
c.Expression = "iqty * irate";
item.Columns.Add(c);
DataColumn[] pk = new DataColumn[1];
pk[0] = item.Columns[0];
item.PrimaryKey = pk;
//to add data in table
DataRow r;
r = item.NewRow();
r[1] = "Pen";
r[2] = 10;
r[3] = 4;
item.Rows.Add(r);
r = item.NewRow();
r[1] = "Scale";
r[2] = 5;
r[3] = 7;
item.Rows.Add(r);
r = item.NewRow();
r[1] = "computer";
r[2] = 25000;
r[3] = 2;
- 135 -
item.Rows.Add(r);
r = item.NewRow();
r[1] = "Laptop";
r[2] = 70000;
r[3] = 1;
item.Rows.Add(r);
GridView1.DataSource = item;
GridView1.DataBind();
TextBox1.Text = item.Compute("Sum(iamt)",
null).ToString();
// null is for filter or we can write condition like "iamt>500"
}
Relation of Tables
protected void Page_Load(object sender, EventArgs e)
{
DataTable dep = new DataTable("tbdep");
dep.Columns.Add(new DataColumn("dno",
Type.GetType("System.Int32")));
dep.Columns.Add(new DataColumn("dname",
Type.GetType("System.String")));
DataRow r;
r = dep.NewRow();
r[0] = 1;
r[1] = "Information Technology";
dep.Rows.Add(r);
r = dep.NewRow();
r[0] = 2;
r[1] = "Civil";
dep.Rows.Add(r);
r = dep.NewRow();
r[0] = 3;
r[1] = "Electronics";
dep.Rows.Add(r);
r = dep.NewRow();
r[0] = 4;
r[1] = "Electrical";
- 136 -
dep.Rows.Add(r);
DataTable emp = new DataTable("tbemp");
emp.Columns.Add(new DataColumn("empno",
Type.GetType("System.Int32")));
emp.Columns.Add(new DataColumn("ename",
Type.GetType("System.String")));
emp.Columns.Add(new DataColumn("eadd",
Type.GetType("System.String")));
emp.Columns.Add(new DataColumn("esal",
Type.GetType("System.Int32")));
emp.Columns.Add(new DataColumn("edno",
Type.GetType("System.Int32")));
//Foreign key
DataColumn c1 = emp.Columns[4];//Child
DataColumn c2 = dep.Columns[0];//Parent
DataSet ds = new DataSet();
ds.Tables.Add(emp);
ds.Tables.Add(dep);
DataRelation rel = new DataRelation("myrelation",
c2, c1);
ds.Tables[0].ParentRelations.Add(rel);
//Always child make a relation with parent not vice versa
r = emp.NewRow();
r[0] = 1;
r[1] = "Amit";
r[2] = "Ambala";
r[3] = 20000;
r[4] = 1;
emp.Rows.Add(r);
r = emp.NewRow();
r[0] = 1;
r[1] = "Amit";
r[2] = "Ambala";
r[3] = 20000;
r[4] = 2;
emp.Rows.Add(r);
// Enter edno dno which is available in dep table only otherwise error
}
- 137 -
ASSEMBLIES
- 138 -
Types of Assemblies
Private Assemblies
Share Assemblies
Satellite Assemblies
DLL are Private assemblies (copy in Bin Folder)
Share Assembly
Single copy share by multiple user
Use less space on server
W can create multiple versions with the help of Strong Name
Strong Name
Uniqueness define karta hai
Multiple versions store karta hai
It uses hashing technique known as Public Key Cryptography
Multiple versions are maintain by Global Assembly Cache (GAC)
GAC is available at C:\windows\Assembly\...
Satellite Assemblies is used to create site in multiple languages(Hindi, English)
If DLL Project me add ho jaye toh woh Private hai otherwise Shared hai.
Start All Programs Ms Visual Studio 2005 Visual Studio tools Visual
Studio Command Prompt
Cd\
Cd ClassLibrary1
Cd ClassLibrary1
Cd obj
Cd Debug
Sn k abc.snk
To write in output file
Strong Name command
In ClassLibrary class1.cs solution explorer properties
AssemblyInfo.cs
In last write
[Assembly: AssemblyKeyFile(abc.snk)] and compile it
In Command prompt write
> GacUtil -I ClassLibrary1
Copy to GAC
GAC utility (to add version in GAC)
Now Add DLL in project
Website Add reference browse classLibrary1 obj debug DLL file
- 139 -
If u want to change in DLL file just make it in same file then compile it and
again give a strong name and change the name in AssemblyInfo file n then
add to GAC.
User using older version will get only old methods but new user get all
methods
- 140 -
o we can store
Bit map
Icons
Common messages
o They are compiled
o Compressed data
In page place DropDownList
o Edit Items
Text English
Value en-us
Text French
Value fr-be
Text German
Value de-at
Add Global Application class
o Global.asax
o Ek project me ek hi ho sati hai
o To manage application ans session events
- 141 -
// jitni baar page server par jata hai yeh event fire hota hai
try
{
Thread.CurrentThread.CurrentCulture=new CultureInfo
(Request.UserLanguages[0].ToString());
}
catch
{
Thread.CurrentThread.CurrentCulture = new
CultureInfo("en-us");
}
Thread.CurrentThread.CurrentUICulture =
Thread.CurrentThread.CurrentCulture;
}
Coding
using System.Resources;
using System.Threading;
// we use threads coz we dont want to change the language of browser but the language
of current instance of browser
using System.Globalization;
// in this there is culture specfic classes
public partial class _Default : System.Web.UI.Page
{
ResourceManager rm;
protected void Page_Load(object sender, EventArgs e)
{
rm = (ResourceManager)(Application["ab"]);
if (Page.IsPostBack == false)
{
Label1.Text = rm.GetString("A");
Label2.Text = rm.GetString("B");
Label3.Text = rm.GetString("C");
Label4.Text = rm.GetString("D");
}
}
private void SetCul(String d)
{
Thread.CurrentThread.CurrentUICulture = new
CultureInfo(d);
// change language of current thread
Label1.Text = rm.GetString("A");
Label2.Text = rm.GetString("B");
Label3.Text = rm.GetString("C");
Label4.Text = rm.GetString("D");
- 142 -
}
protected void DropDownList1_SelectedIndexChanged()
{
SetCul(DropDownList1.SelectedValue);
}
}
State Management
- 143 -
Web Form are stateless in nature which means when request goes to server pages
loose their information like registration form loose data when we come back.
State management techniques have been introduced to store page information in
server around trip.
Technology divided into two parts
o Server side state management technique
It uses resources of server to store information
Secure as the information is on server.
Slow.
o Client side state management technique
It uses resources of client to store information.
It less secure as compare to server side coz it is at client side user can
manipulate or delete it.
It is faster than server side.
4 technology included in client side state management
o Cookies
o View state
o Query string
o Hidden fields
o Control state (in Asp.Net 2.0 only)
4 technology included in server side state management
o Sessions
o Application
o Profile (in Asp.Net 2.0 only)
o Cache
To check there performance we check three things according to our requirement
o Storing capacity
o Type of information
o Scope
o
o
o
o
o
o
o
o
o
o
o
Query String
o It is used to transfer text as well as numeric information between continues
page requests.(string value only)
o The information is concentrated with URL.
o Disadvantage
Information can be seen by user so not so secure
Internet URL limit (2096 characters)
o Scope
Upto next page.
Hidden Field
o Advance of hidden fields is view state
o In this we can only store text not object
o Scope
Only on current page
Control State
o In this custom control (made by programmer) ki state management hoti hai
Server Side State Management
Application
o When first user site kholta hai Application Start event fire hota hai
o Application Start event ek hi baar fire hota hai.
o When another user site kholta hai HTTP Application class ka instance
banta hai.
o Application End event tab fire hota hai jab last visitor site band karta hai,
yeh event bhi ek hi bar fire hota hai. Jab yeh fire hota hai iske baad
Application Start event fire hota hai.
o Application variable can be string as well as objects
- 146 -
- 147 -
Profile
o To set colors, themes , back ground etc different for different users.
o Two types of users
Authenticated (inka profile ASP.Net db me store hota hai)
Unauthenticated (inka cookies me store hota hai)
Cookies
Add new page and place two textboxes, a label and a button
{
Label1.Text="check username & password";
}
}
}
/////////////////////////////////////////////////////////////
Response.Cookies["un"].Value = "abc";
Response.Cookies["un"].Expires =
DateTime.Now.AddHours(2);
/////////////////////////////////////////////////////////////
HttpCookie kk = new HttpCookie("un", "abc");
k.Expires = DateTime.Now.AddHours(2);
Response.Cookies.Add(k);
/////////////////////////////////////////////////////////////
//Cookies with sub keys
/////////////////////////////////////////////////////////////
Response.Cookies["ui"]["un"] = "abc";
Response.Cookies["ui"]["up"] = "xyz";
Response.Cookies["ui"].Expires =
DateTime.Now.AddHours(2);
///////////////////////////////////////////////////////////
HttpCookie kkk = new HttpCookie("ui");
kkk.Value["un"] = "abc";
kkk.Value["up"] = "xyz";
kkk.Expires = DateTime.Now.AddHours(2);
Response.Cookies.Add(kkk);
////////////////////////////////////////////////////////////
// To Read Value//
///////////////////////////////////////////////////////////
Response.Write(Request.Cookies["un"].Value);
///////////////////////////////////////////////////////////
HttpCookie d = Request.Cookies["un"];
Response.Write(d.Value);
//////////////////////////////////////////////////////////
- 149 -
- 150 -
QueryString
- 151 -
<head runat="server">
<title>Untitled Page</title>
<script language=javascript>
function abc(id)
{
window.open("default2.aspx?ab="+id,"name",
"height=350,width=350");
// To open sub Window
}
</script>
</head>
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Button1.Attributes.Add("OnClick",
"abc('form1.textbox1');");
}
Default2.aspx
protected Calendar1_DayRender(object,DayRenderEventArgs)
{
//Fire for each day
e.Cell.Controls.Clear();
HtmlGenericControl lk = new HtmlGenericControl();
// Kisi bhi tag ka kaam karwa sakte hai
lk.TagName = "a";
lk.InnerText = e.Day.DayNumberText;
lk.Attributes["href"] =
String.Format("javascript:window.
- 152 -
opener.document.{0}.value='{1}';window.close()",
Request.QueryString["ab"].ToString(),
e.Day.Date.ToShortDateString());
e.Cell.Controls.Add(lk);
}
Place a label
protected void Page_Load(object , EventArgs e)
{
if (Request.QueryString["aa"] == null)
{
HttpCookie ck = new HttpCookie("myckk",
"sachin");
ck.Expires = DateTime.Now.AddDays(2);
Response.Cookies.Add(ck);
Response.Redirect("default2.aspx?aa=" +
Request.Url.ToString());
// To fetch url of current page use Request.Url
}
else
{
Label1.Text =
Request.QueryString["aa"].ToString();
}
}
Default2.aspx.cs
protected void Page_Load(object , EventArgs e)
{
String d, d1;
d = Request.QueryString["aa"].ToString();
HttpCookie k = Request.Cookies["myckk"];
if (k == null)
{
d1 = "cookie not created";
}
else
{
d1 = "cookie created";
k.Expires = DateTime.Now.AddDays(-1);
// To expire cookie forcefully
Response.Cookies.Add(k);
- 153 -
}
Response.Redirect(d + "?aa=" + d1);
}
ViewState
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds;
if (ViewState["abc"] == null)
{
ds = GetData();
ViewState["abc"] = ds;
Label1.Text = "Read Data from Database";
}
else
{
ds = (DataSet)(ViewState["abc"]);
Label1.Text = "Read data from Viewstate";
}
GridView1.DataSource = ds;
GridView1.DataBind();
}
private DataSet GetData()
{
SqlDataAdapter adp = new SqlDataAdapter("select *
from tbemp", "database=dbemp;uid=sa");
DataSet ds = new DataSet();
adp.Fill(ds);
return ds;
}
}
- 154 -
Default.aspx.cs
protected void Page_Load(object ,EventArgs)
{
Label1.Text = Application["ctr"].ToString();
}
Session
If u want to use one object thoughout the session use session object and if u want
to use one object only one one page use application.
Place a button
using System.Data.SqlClient;
protected void Button1_Click(object, EventArgs e)
{
SqlDataAdapter adp = new SqlDataAdapter("select*
from tbemp", "database=dbemp;uid=sa");
DataSet ds = new DataSet();
adp.Fill(ds);
Session["ss"] = ds;
Response.Redirect("default2.aspx");
}
Default2.aspx
Session State
- 157 -
InProcess(By default)
OutProcess
Start IIS server from control panel add remove files windows
components
Open new application
Select Location Http , name http://Localhost/aaa
Place Button
Place label
protected void Page_Load(object, EventArgs e)
{
if (Session["ss"] != null)
{
Label1.Text = Session["ss"].ToString();
}
else
{
Label1.Text = "No Data";
}
}
Out Process
State Service
<system.web>
<sessionState mode="StateServer"
stateConnectionString="tcpip=127.0.0.1:42424"
timeout="20"></sessionState>
- 158 -
SQL Server
<system.web>
<sessionState mode="SQLServer"
sqlConnectionString="server=cs;uid=sa">
</sessionState>
- 159 -
Where:
-S server
sac server name
-E current user instance
-U admin P password (if user is sepecficed)
-ssadd session state add database
-sstype session state type
T temporary
P permanent
In TempDb data is store in ASPStateTempSessions and if we reset
SQLServerService data will lost
In ASPStateDb data is permanent.
Shopping Cart
Default.aspx
<ItemTemplate>
<b>Title:</b><asp:LinkButton Text=<%#Eval("bookTitle")%>
CommandName="Select"
runat="server"></asp:LinkButton><br />
<b>Author:</b><%#Eval("BookAuthor")%><br />
<asp:ImageButton ID="img1" ImageUrl="~/go_login.gif"
CommandName="Cart" runat="server" />
</ItemTemplate>
- 160 -
Default2.aspx
Place a DetailView
<Fields>
<asp:TemplateField HeaderText="Id">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#
Eval("bookId") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:Label ID="Label2" runat="server"
Text='<%# Eval("bookTitle") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Author">
<ItemTemplate>
<asp:Label ID="Label3" runat="server"
Text='<%# Eval("bookAuthor") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Publisher">
<ItemTemplate>
<asp:Label ID="Label4" runat="server"
Text='<%# Eval("BookPub") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="Label5" runat="server"
Text='<%# Eval("BookPrice") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server"
OnClick="Button1_Click" Text="Button" />
</ItemTemplate>
</asp:TemplateField>
- 161 -
</Fields>
using System.Data.SqlClient;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String st = "Select * from tbBook where bookId=" +
Request.QueryString["bid"].ToString();
SqlDataAdapter adp=new SqlDataAdapter(st,
ConfigurationManager.ConnectionStrings["cs"].
ConnectionString);
DataSet ds = new DataSet();
adp.Fill(ds);
DetailsView1.DataSource = ds;
DetailsView1.DataBind();
}
protected void DetailsView1_ItemCommand(object, e)
{
}
protected void Button1_Click(object , EventArgs e)
{
Response.Redirect("default3.aspx?bid=" +
((Label)(DetailsView1.FindControl("label1"))).Text);
}
}
Default3.aspx
Place GridView
- 163 -
ConfigurationManager.ConnectionStrings["cs"].
ConnectionString);
DataSet ds = new DataSet();
adp.Fill(ds);
DataRowView r; // for one row
r = ds.Tables[0].DefaultView[0];
DataTable ab = (DataTable)(Session["ss1"]);
DataRow r1 = ab.NewRow();
r1[0] = Convert.ToInt32(r["bookId"]);
r1[1] = r["bookTitle"].ToString();
r1[2]=r["bookAuthor"].ToString();
r1[3] = r["BookPub"].ToString();
r1[4]=Convert.ToInt32(r["BookPrice"]);
r1[5] = 1;
ab.Rows.Add(r1);
GridView1.DataSource = ab;
GridView1.DataBind();
}
}
public void GrdBind()
{
GridView1.DataSource = (DataTable)(Session["ss1"]);
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, e)
{
GridView1.EditIndex = e.NewEditIndex;
GrdBind();
}
protected void GridView1_RowUpdating(object sender, e)
{
DataTable tt = (DataTable)(Session["ss1"]);
tt.Rows[e.RowIndex][5] = Convert.ToInt32(((TextBox)
(GridView1.Rows[e.RowIndex].Cells[5].
Controls[0])).Text);
GridView1.EditIndex = -1;
GrdBind();
}
protected void GridView1_RowCancelingEdit(object, e)
{
GridView1.EditIndex = -1;
GrdBind();
}
}
- 164 -
SECURITY
Security include
1. Authorization means permission to user.
2. Authentication
Authentication of IIS
1. Basic Authentication In basic authentication user password stored into cleared
text.
2. Digest AuthenticationThis authentication is by default provided by IIS and user
password stored in encrypted form.
3. Window Integrating AuthenticationUser of window.
Authentication Types
1. Window AuthenticationIt is by default authentication.
2. Forms
(a). Forms Authentication It is customized authentication and used mostly.
3. Passport Authentication with single sign in we can login into multiple passport
Enable sites.
4. None
We can also create user and password in webconfig and xml file.
Membership and role is a new feature in 2.0
FORM AUTHENTICATION
1.Add webconfig file
Username
Password
Button
Webconfig file
<authentication mode="Forms">
<forms name="cookie" loginUrl="login.aspx"></forms>
- 165 -
</authentication>
Login.aspx
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;
public partial class login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text == "faisal" && TextBox2.Text == "khan")
{
FormsAuthentication.RedirectFromLoginPage
(TextBox1.Text,false);
}
else
{
Response.Write("Wrong user/password");
}
}
}
FormsAuthentication.RedirectFromLoginPage(TextBox1.Text,false)user name ko
cookie mai likhega aur redirect to default page.
Default.aspx
Label
using System;
using System.Data;
using System.Configuration;
using System.Web;
- 166 -
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated)
{
Label1.Text = "Welcome :" + User.Identity.Name;
}
else
{
FormsAuthentication.RedirectToLoginPage();
}
}
}
HOW USER AUTHENTICATE IN WEB CONFIG FILE
Webconfig file
<authentication mode="Forms">
<forms name="cookie" loginUrl="login.aspx">
<credentials passwordFormat ="Clear">
<user name ="admin" password ="ad"/>
<user name ="admin1" password ="ad1"/>
</credentials>
</forms>
</authentication>
Login.aspx
Username
Password
Button2
- 167 -
false);
}
else
{
Response.Write("Wrong user/password");
}
}
Specific Autherity
</system.web>
<location path ="default2.aspx">
<system.web >
<authorization >
<allow users ="admin"/>
<deny users ="*"/>
</authorization>
</system.web>
</location>
<location path ="default3.aspx">
<system.web >
<authorization >
<allow users ="admin1"/>
<deny users ="*"/>
</authorization>
</system.web>
</location>
* Means deny autherisation and unautherisation user.
? Means deny unauthenticated.
Default.aspx
2 hyperlink button
PropertyNavigationURLDefault2.aspx
PropertyNavigationURLDefault3.aspx
- 168 -
Uname varchar(50)
Upass varchar(50)
Urole varchar(50)
Upass
Urole
Faisal
khan
admin
Sachin
gupta
user
Charu
satia
admin|user
Adm--> default2.aspx,default3.aspx
Usr-->default4.aspx,default5.aspx
<authentication mode="Forms">
<forms name="cookie" loginUrl="login.aspx">
</forms>
</authentication>
</system.web>
<location path ="adm">
<system.web >
<authorization >
<allow roles ="admin"/>
<deny users ="*"/>
</authorization>
</system.web>
</location>
<location path ="usr">
<system.web >
<authorization >
<allow roles ="user"/>
<deny users ="*"/>
- 169 -
</authorization>
</system.web>
</location>
Login.aspx
Username
Password
Button
using System.Data.SqlClient;
public partial class login1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "database=emp;uid=sa";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from tbauth1 where uname=@u and upass=@p";
cmd.Parameters.Add("@u", SqlDbType.VarChar, 50).Value =TextBox1.Text;
cmd.Parameters.Add("@p", SqlDbType.VarChar, 50).Value =TextBox2.Text;
cmd.Connection = con;
SqlDataReader dr;
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dr.Read();
FormsAuthenticationTicket tkt = new
FormsAuthenticationTicket(1, TextBox1.Text,
DateTime.Now, DateTime.Now.AddMinutes(10), false,
dr[2].ToString(), FormsAuthentication.FormsCookiePath);
//Here we encrypt the ticket n stored st(ticket) and cookie name from
webconfig file into cookie or with the help of querystring passed this value
into default.aspx
- 170 -
string st;
st = FormsAuthentication.Encrypt(tkt);
HttpCookie ck = new
HttpCookie(FormsAuthentication.FormsCookieName, st);
Response.Cookies.Add(ck);
Response.Redirect("default.aspx");
}
else
{
Response.Write("wrong user/password");
}
dr.Close();
cmd.Dispose();
}
}
How authenticate user access the file so a Add global application class
Global Application Class
Namespace System.Security.Principal contain generic principal class which is
combination of identity & roles is known as generic principal.
Select application and his event AuthenticateRequest .
Event AuthenticateRequest fire every time for user check.
HttpContextEnclupulate all http specific information about an individual http request.
- 171 -
Default.aspx
2 Hyperlink Button
PropertyNavigationURLadm/Default2.aspx,Default3.aspx
PropertyNavigationURLusr/Default4.aspx,Default5.aspx
- 173 -