chottu sharma notes

220
It’s me - 1 -

Upload: gaurav-singh

Post on 21-Nov-2014

212 views

Category:

Documents


32 download

TRANSCRIPT

Page 1: Chottu Sharma Notes

It’s me - 1 -

Page 2: Chottu Sharma Notes

INTRODUCTION

ASP 2.0 using c# or VB.netDatabase SQL Server, Xml

It is used for web development

.Net Architecture

ASP.Net web Application BCL Windows Application

CLR

OS

BCL Base class languageCLR Common Language RuntimeOS 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 languageE.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

It’s me - 2 -

Page 3: Chottu Sharma Notes

In web development application run on server. At client side there is simple Html page which is understand by a browser

Server in .net case is Microsoft(running n developing environment)

.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

Connection of tools, technology n language which work together to communicate on multiple platform.

To run .net application we must have .net framework Framework is made in Perl language.

Version of .net Framework

1.0 (visual studio 2000) beta or testing version 1.1 (visual studio 2003) 17/4/03 2.0 (visual studio 2000) 7/11/05

In 1.1 we cover 4 languages Vb.net C# C++.net Jscript.net

We added one more language in 2.0 J#

If we use BCL then there is no difference in these languages We can use multiple languages in an application

Compilation of .net application

Different compiler

VB.net C1

C# C2 MSIL JIT Native code

J# C3

MSIL Microsoft Intermediate Language (m/c independent)

It’s me - 3 -

Page 4: Chottu Sharma Notes

We must have JIT( just in time) compiler at server which make native code which is m/c dependent n CPU specific

Advantages of JIT:

Jitna code chahiye utna hi compile karte hai Ek baar native code banana ke baad dubara nahi banate

Types of JIT:

PRE ECHNO NORMAL

Compilation modes in ASP.Net 2.0

In place compilation (by default) Single file compiler at run time in which changes has been done. Used on the sites where changes are done regularly One disadvantage of this is that we need source code)

Site pre compilation It use compiler name as “ASPnet_compiler”. It makes compilization file for each file starting with “app_web” and after that Any random generated name like abc ----- app_webijhgt xyz ----- app_webgfdf It has better performance It is fast Adv – No source code required Disadvantage – even single change require full compilation of site

Requirements for ASP.Net

ServerIIS (Internet information service) it is used with 1.1 versionIt 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(By default “c:\netpub\wwwroot”)

To check weather server is running or notControl panel --- adm tools --- IIS --- CS ---web sites--- default web site (Right click)---start/stop. If start n stop is working IIS is running

Web Server included in version 2.0

It’s me - 4 -

Page 5: Chottu Sharma Notes

It can run on XP-home edition

XP professional with service pack 2/2003 server with service pack 1/Win 2000 professional service pack 4

Visual studio 2005

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.

We can inherit only one class not multiple inheritance in .net

We differciate method, namespace, property, class by there symbol{ } namespace3 boxes classPink box method etcBijali eventHand property

Namespace is collection of classes it may be nested

All procedures which have handles in the end are events.

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

It’s me - 5 -

Page 6: Chottu Sharma Notes

Solution explorer Toolbox

HTML Control (background compatibility)Run on client side and are browser dependent

Web Server controlRun 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:

Display current date & time in label

Sub Page_loadLabel1.text = datetime.now

End sub

In c#Void page_load (){

Label1.text = datetime.now.toString();}

To run a code only first time the page is loaded we use

If page.isPostBack = false thenLabel1.text = datetime.now

End if

page.isPostBack is false only first time when page is loaded. It is read-only.

To stop scrolling of window when page is posted back

Me.SmartNavigation = true

To compile line by line click in front of line where u want to place break and then press f10.

To add two numbers

It’s me - 6 -

Page 7: Chottu Sharma Notes

Textbox3.text = convert.Toint32(textbox1.text) + convert.Toint32(textbox2.text);

In C#

Textbox3.text=convert.Tostring(convert.Toint32 (textbox1.text) +convert.Toint32(textbox2.text));

In Vb.net type casting is automatic but in C# we have to do it manually.

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 thenSum

Else if sender is button4 thenMul

ElseDivide

In C#We change in HTML, use onClick method for this purpose

It’s me - 7 -

Page 8: Chottu Sharma Notes

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. Advantages of both languages 2. Keyword Differences 3. Data types Differences 4. Operators Differences 5. Programming Difference

Advantages of both languages

VB.NET C#

Support for optional parameters - very handy for some COM interoperability.

Support for late binding with Option Strict off - type safety at compile time goes out of the window, but legacy libraries which don't have strongly typed interfaces become easier to use.

Support for named indexers. Various legacy VB functions (provided in

the Microsoft.VisualBasic namespace, and can be used by other languages with a reference to the Microsoft.VisualBasic.dll). Many of these can be harmful to performance if used unwisely, however, and many people believe they should be avoided for the most part.

The with construct: it's a matter of debate as to whether this is an advantage or not, but it's certainly a difference.

Simpler (in expression - perhaps more complicated in understanding) event handling, where a method can declare that it handles an event, rather than the handler having to be set up in code.

The VB.NET parts of Visual Studio .NET compiles your code in the background. While this is considered as an advantage for small projects, people creating very large projects have found that the IDE slows down considerably as the project gets larger.

XML documentation generated from source code comments. (This is coming in VB.NET with Whidbey (the code name for the next version of Visual Studio and .NET), and there are tools which will do it with existing VB.NET code already.)

Operator overloading - again, coming to VB.NET in Whidbey.

Language support for unsigned types (you can use them from VB.NET, but they aren't in the language itself). Again, support for these is coming to VB.NET in Whidbey.

Explicit interface implementation, where an interface which is already implemented in a base class can be re-implemented separately in a derived class. Arguably this makes the class harder to understand, in the same way that member hiding normally does.

Unsafe code. This allows pointer arithmetic etc, and can improve performance in some situations. However, it is not to be used lightly, as a lot of the normal safety of C# is lost (as the name implies). Note that unsafe code is still managed code, i.e., it is compiled to IL, JITted, and run within the CLR.

It’s me - 8 -

Page 9: Chottu Sharma Notes

Keyword Differences

Purpose VB.NET C#

Declare a variable Private, Public, Friend, Protected, Static1, Shared, Dim

declarators (keywords include user-defined types and built-in types)

Declare a named constant

Const const

Create a new object New, CreateObject() new

Function/method does not return a value

Sub void

Overload a function or method (Visual Basic: overload a procedure or method)

Overloads (No language keyword required for this purpose)

Refer to the current object

Me this

Make a nonvirtual call to a virtual method of the current object

MyClass n/a

Retrieve character from a string

GetChar Function []

Declare a compound data type (Visual Basic: Structure)

Structure <members> End Structure

struct, class, interface

Initialize an object (constructors)

Sub New() Constructors, or system default type constructors

Terminate an object directly

n/a n/a

Method called by the system just before garbage collection reclaims an object7

Finalize destructor

Initialize a variable where it is declared

Dim x As Long = 5Dim c As New _ Car(FuelTypeEnum.Gas)

// initialize to a value:int x = 123;// or use default // constructor:int x = new int();

Take the address of a function

AddressOf (For class members, this operator returns a reference to a function in the form of a

delegate

It’s me - 9 -

Page 10: Chottu Sharma Notes

delegate instance)

Declare that an object can be modified asynchronously

n/a volatile

Force explicit declaration of variables

Option Explicit n/a. (All variables must be declared prior to use)

Test for an object variable that does not refer to an object

obj = Nothing obj == null

Value of an object variable that does not refer to an object

Nothing null

Test for a database null expression

IsDbNull n/a

Test whether a Variant variable has been initialized

n/a n/a

Define a default property

Default by using indexers

Refer to a base class MyBase base

Declare an interface Interface interface

Specify an interface to be implemented

Implements (statement) class C1 : I1

Declare a class Class <implementation> class

Specify that a class can only be inherited. An instance of the class cannot be created.

MustInherit abstract

Specify that a class cannot be inherited

NotInheritable sealed

Declare an enumerated type

Enum <members> End Enum enum

Declare a class constant

Const const (Applied to a field declaration)

Derive a class from a base class

Inherits C2 class C1 : C2

Override a method Overrides override

Declare a method that must be implemented in a deriving class

MustOverride abstract

It’s me - 10 -

Page 11: Chottu Sharma Notes

Declare a method that can't be overridden

NotOverridable (Methods are not overridable by default.)

sealed

Declare a virtual method, property (Visual Basic), or property accessor (C#, C++)

Overridable virtual

Hide a base class member in a derived class

Shadowing n/a

Declare a typesafe reference to a class method

Delegate delegate

Specify that a variable can contain an object whose events you wish to handle

WithEvents (Write code - no specific keyword)

Specify the events for which an event procedure will be called

Handles (Event procedures can still be associated with a WithEvents variable by naming pattern.)

n/a

Evaluate an object expression once, in order to access multiple members

With objExpr <.member> <.member> End With

n/a

Structured exception handling

Try <attempt>Catch<handle errors>Finally<always execute>End Try

try, catch, finally, throw

Decision structure (selection)

Select Case ..., Case, Case Else, End Select

switch, case, default, goto, break

Decision structure (if ... then)

If ... Then, ElseIf ... Then, Else, End If

if, else

Loop structure (conditional)

While, Do [While, Until] ..., Loop [While, Until]

do, while, continue

Loop structure (iteration)

For ..., [Exit For], NextFor Each ..., [Exit For,] Next

for, foreach

Declare an array Dim a() As Long int[] x = new int[5];

It’s me - 11 -

Page 12: Chottu Sharma Notes

Initialize an array Dim a() As Long = {3, 4, 5}

int[] x = new int[5] { 1, 2, 3, 4, 5};

Reallocate array Redim n/a

Visible outside the project or assembly

Public public

Invisible outside the assembly (C#/Visual Basic) or within the package (Visual J#, JScript)

Friend internal

Visible only within the project (for nested classes, within the enclosing class)

Private private

Accessible outside class and project or module

Public public

Accessible outside the class, but within the project

Friend internal

Only accessible within class or module

Private private

Only accessible to current and derived classes

Protected protected

Preserve procedure's local variables

Static n/a

Shared by all instances of a class

Shared static

Comment code 'Rem

//, /* */ for multi-line comments/// for XML comments

Case-sensitive? No Yes

Call Windows API Declare <API> use Platform Invoke

Declare and raise an event

Event, RaiseEvent event

Threading primitives SyncLock lock

Go to Goto goto

It’s me - 12 -

Page 13: Chottu Sharma Notes

Data types Differences

Purpose/Size VB.NET C#

Decimal Decimal decimal

Date Date DateTime

(varies) String string

1 byte Byte byte

2 bytes Boolean bool

2 bytes Short, Char (Unicode character)

short, char (Unicode character)

4 bytes Integer int

8 bytes Long long

4 bytes Single float

8 bytes Double double

Operators Differences

Purpose VB.NET C#

Integer division \ /

Modulus (division returning only the remainder)

Mod %

Exponentiation ^ n/a

Integer division Assignment

\= /=

Concatenate &= NEW +=

Modulus n/a %=

Bitwise-AND n/a &=

Bitwise-exclusive-OR n/a ^=

Bitwise-inclusive-OR n/a |=

Equal = ==

Not equal <> !=

Compare two object Is ==

It’s me - 13 -

Page 14: Chottu Sharma Notes

reference variables

Compare object reference type

TypeOf x Is Class1 x is Class1

Concatenate strings & +

Shortcircuited Boolean AND

AndAlso &&

Shortcircuited Boolean OR

OrElse ||

Scope resolution . . and base

Array element () [ ]

Type cast Cint, CDbl, ..., CType (type)

Postfix increment n/a ++

Postfix decrement n/a --

Indirection n/a * (unsafe mode only)

Address of AddressOf & (unsafe mode only; also see fixed)

Logical-NOT Not !

One's complement Not ~

Prefix increment n/a ++

Prefix decrement n/a --

Size of type n/a sizeof

Bitwise-AND And &

Bitwise-exclusive-OR Xor ^

Bitwise-inclusive-OR Or |

Logical-AND And &&

Logical-OR Or ||

Conditional If Function () ?:

Pointer to member n/a . (Unsafe mode only)

Programming Difference

Purpose VB.NET C#

Declaring Variables

Dim x As IntegerPublic x As Integer = 10

int x;int x = 10;

Comments ' commentx = 1 ' commentRem comment

// comment/* multiline comment */

Assignment Statements

nVal = 7 nVal = 7;

Conditional If nCnt <= nMax Then if (nCnt <= nMax)

It’s me - 14 -

Page 15: Chottu Sharma Notes

Statements ' Same as nTotal = ' nTotal + nCnt. nTotal += nCnt ' Same as nCnt = nCnt + 1. nCnt += 1 Else nTotal += nCnt nCnt -= 1 End If

{ nTotal += nCnt; nCnt++;}else{ nTotal +=nCnt; nCnt--;}

Selection Statements

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

switch(n) { case 0: Console.WriteLine("Zero"); break; case 1: Console.WriteLine("One"); break; case 2: Console.WriteLine("Two"); break; default: Console.WriteLine("?"); break;}

FOR Loops For n = 1 To 10 MsgBox("The number is " & n)Next

For Each prop In obj prop = 42Next prop

for (int i = 1; i <= 10; i++) Console.WriteLine( "The number is {0}", i);foreach(prop current in obj){ current=42;}

Hiding Base Class Members

Public Class BaseCls ' The element to be shadowed Public Z As Integer = 100 public Sub Test() System.Console.WriteLine( _ "Test in BaseCls") End SubEnd Class

Public Class DervCls Inherits BaseCls ' The shadowing element. Public Shadows Z As String = "*" public Shadows Sub Test() System.Console.WriteLine( _ "Test in DervCls")

public class BaseCls{ // The element to be hidden public int Z = 100; public void Test() { System.Console.WriteLine( "Test in BaseCls"); }}

public class DervCls : BaseCls{ // The hiding element

It’s me - 15 -

Page 16: Chottu Sharma Notes

End SubEnd Class

Public Class UseClasses ' DervCls widens to BaseCls. Dim BObj As BaseCls = New DervCls() ' Access through derived ' class. Dim DObj As DervCls = New DervCls()

Public Sub ShowZ() System.Console.WriteLine( _ "Accessed through base "&_ "class: " & BObj.Z) System.Console.WriteLine(_ "Accessed through derived "&_ "class: " & DObj.Z) BObj.Test() DObj.Test() End Sub End Class

public new string Z = "*"; public new void Test() { System.Console.WriteLine( "Test in DervCls"); }}

public class UseClasses{ // DervCls widens to BaseCls BaseCls BObj = new DervCls(); // Access through derived //class DervCls DObj = new DervCls(); public void ShowZ() { System.Console.WriteLine( "Accessed through " + "base class: {0}", BObj.Z); System.Console.WriteLine( "Accessed through" + " derived class:{0}", DObj.Z); BObj.Test(); DObj.Test();  }}

WHILE Loops

' Test at start of loopWhile n < 100 . ' Same as n = n + 1. n += 1 End While '

while (n < 100) n++;

Parameter Passing by Value

' The argument Y is 'passed by value.Public Sub ABC( _ ByVal y As Long) 'If ABC changes y, the' changes do not affect x.End Sub ABC(x) ' Call the procedure.' You can force parameters to ' be passed by value, ' regardless of how ' they are declared, ' by enclosing ' the parameters in ' extra parentheses.

/* Note that there is no way to pass reference types (objects) strictly by value. You can choose to either pass the reference (essentially a pointer), or a reference to the reference (a pointer to a pointer).*/// The method:void ABC(int x){ ...}// Calling the method:ABC(i);

It’s me - 16 -

Page 17: Chottu Sharma Notes

ABC((x))

Parameter Passing by Reference

Public Sub ABC(ByRef y As Long) ' The parameter y is declared 'by referece:' If ABC changes y, the changes are' made to the value of x.End Sub

ABC(x) ' Call the procedure.

/* Note that there is no way to pass reference types (objects) strictly by value. You can choose to either pass the reference (essentially a pointer), or a reference to the reference (a pointer to a pointer).*/// Note also that unsafe C# //methods can take pointers //just like C++ methods. For //details, see unsafe.// The method:void ABC(ref int x){ ...}// Calling the method:ABC(ref i);

Structured Exception Handling

Try If x = 0 Then Throw New Exception( _ "x equals zero") Else Throw New Exception( _ "x does not equal zero") End IfCatch err As System.Exception MsgBox( _ "Error: " & Err.Description)Finally MsgBox( _ "Executing finally block.")End Try

// try-catch-finallytry{ if (x == 0) throw new System.Exception( "x equals zero"); else throw new System.Exception( "x does not equal zero");}catch (System.Exception err){ System.Console.WriteLine( err.Message);}finally{ System.Console.WriteLine( "executing finally block");}

Set an Object Reference to Nothing

o = Nothing o = null;

Initializing Dim dt as New System.DateTime( _ System.DateTime dt =

It’s me - 17 -

Page 18: Chottu Sharma Notes

Value Types

2001, 4, 12, 22, 16, 49, 844) new System.DateTime( 2001, 4, 12, 22, 16, 49, 844);

New Features of both languages in 2005 version

VB.NET C#

Visual Basic 2005 has many new and improved language features -- such as inheritance, interfaces, overriding, shared members, and overloading -- that make it a powerful object-oriented programming language. As a Visual Basic developer, you can now create multithreaded, scalable applications using explicit multithreading. This language has following new features,

1. Continue Statement, which immediately skips to the next iteration of a Do, For, or While loop.

2. IsNot operator, which you can avoid using the Not and Is operators in an awkward order.

3. Using...End. Using statement block ensures disposal of a system resource when your code leaves the block for any reason.

4. Public Sub setbigbold( _5. ByVal c As Control)6. Using nf As New _7. System.Drawing.Font("Arial",_8. 12.0F, FontStyle.Bold)9. c.Font = nf10. c.Text = "This is" &_11. "12-point Arial bold"12. End Using

With the release of Visual Studio 2005, the C# language has been updated to version 2.0. This language has following new features:

1. Generics types are added to the language to enable programmers to achieve a high level of code reuse and enhanced performance for collection classes. Generic types can differ only by arity. Parameters can also be forced to be specific types.

2. Iterators make it easier to dictate how a for each loop will iterate over a collection's contents.

3. // Iterator Example4. public class NumChar5. {6. string[] saNum = { 7. "One", "Two", "Three", 8. "Four", "Five", "Six", 9. "Seven", "Eight", "Nine", 10. "Zero"};11. public 12.

System.Collections.IEnumerator

13. GetEnumerator()

It’s me - 18 -

Page 19: Chottu Sharma Notes

End Sub

13. Explicit Zero Lower Bound on an Array, Visual Basic now permits an array declaration to specify the lower bound (0) of each dimension along with the upper bound.

14. Unsigned Types, Visual Basic now supports unsigned integer data types (UShort, UInteger, and ULong) as well as the signed type SByte.

15. Operator Overloading, Visual Basic now allows you to define a standard operator (such as +, &, Not, or Mod) on a class or structure you have defined.

16. Partial Types, to separate generated code from your authored code into separate source files.

17. Visual Basic now supports type parameters on generic classes, structures, interfaces, procedures, and delegates. A corresponding type argument specifies at compilation time the data type of one of the elements in the generic type.

18. Custom Events. You can declare custom events by using the Custom keyword as a modifier for the Event statement. In a custom event, you specify exactly what happens when code adds or removes an event handler to or from the event, or when code raises the event.

19. Compiler Checking Options, The /nowarn and /warnaserror options provide more control over how warnings are handled. Each one of these compiler options now takes a list of warning IDs as an optional parameter, to specify to which warnings the option applies.

20. There are eight new command-line compiler options:

a. The /codepage option specifies which codepage to use when opening source files.

b. The /doc option generates an

14. {15. foreach (string num in

saNum)16. yield return num;17. }18. }19. // Create an instance of 20. // the collection class21. NumChar oNumChar = new

NumChar();22. // Iterate through it with

foreach23. foreach (string num in

oNumChar)24. Console.WriteLine(num);

25. Partial type definitions allow a single type, such as a class, to be split into multiple files. The Visual Studio designer uses this feature to separate its generated code from user code.

26. Nullable types allow a variable to contain a value that is undefined.

27. Anonymous Method is now possible to pass a block of code as a parameter. Anywhere a delegate is expected, a code block can be used instead: There is no need to define a new method.

28. button1.Click += 29. delegate

{ MessageBox.Show( "Click!") };

30. . The namespace alias qualifier (::) provides more control over accessing namespace members. The global :: alias allows to access the root namespace that may be hidden by an entity in your code.

31. Static classes are a safe and convenient way of declaring a class containing static methods that cannot be instantiated. In C# v1.2 you would have defined the class constructor as private to prevent the class being instantiated.

It’s me - 19 -

Page 20: Chottu Sharma Notes

XML documentation file based on comments within your code.

c. The /errorreport option provides a convenient way to report a Visual Basic internal compiler error to Microsoft.

d. The /filealign option specifies the size of sections in your output file.

e. The /noconfig option causes the compiler to ignore the Vbc.rsp file.

f. The /nostdlib option prevents the import of mscorlib.dll, which defines the entire System namespace.

g. The /platform option specifies the processor to be targeted by the output file, in those situations where it is necessary to explicitly specify it.

h. The /unify option suppresses warnings resulting from a mismatch between the versions of directly and indirectly referenced assemblies.

32. 8. There are eight new compiler options:

a. /langversion option: Can be used to specify compatibility with a specific version of the language.

b. /platform option: Enables you to target IPF (IA64 or Itanium) and AMD64 architectures.

c. #pragma warning: Used to disable and enable individual warnings in code.

d. /linkresource option: Contains additional options.

e. /errorreport option: Can be used to report internal compiler errors to Microsoft over the Internet.

f. /keycontainer and /keyfile: Support specifying cryptographic keys.

It’s me - 20 -

Page 21: Chottu Sharma Notes

VALIDATION AND CHECKS

Validations are provided by Microsoft in Vb.net Run on client site. In asp JavaScript will not run if client site don’t have JavaScript In .net if not jscript at client then they run on server.

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

Required field validation properties

controlToValidate name of textbox to check Text message

Compare validation properties

It’s me - 21 -

Page 22: Chottu Sharma Notes

controlToValidate name of first textbox to check Text message controlToValidate name of second textbox to check

For value check controlToValidate name of textbox to check valueToCompare value to check operator greater, less, equal etc type integer Text message

For salary must be number check controlToValidate name of textbox to check operator Data type check type integer Text message

For range check controlToValidate name of textbox to check minimumValue value maximumValue value Text message

For valid email address check controlToValidate name of textbox to check ValidationExpression Popup window Text message

Validation summary

Ek jagha sare error n asterisk sign in front of error Text property value display on validator and error message display on the validation

summary.Text *errorMessage Empno empty

To run validation summary we need a button To make popup window go to validation summary property

ShowMessageBox trueShow Summary false

Addition properties in version 2.0 set the causes validation property to false to disable the validation of button validation group property of validator (textbox, validationSummary n of button)

o ValidationGroup a property of validator

It’s me - 22 -

Page 23: Chottu Sharma Notes

o SetfocusonError to go directly to the error point skip correct places. Add more than one page in website (Click on website add new item webform)

To Make startup page (go to solution explorer right click on page set as start page).

To go to new page we have 3 methodso Response.redirect()o Server.transfer()o Server.execute()

To go to next page by buttono Response.redirect(“default.aspx”)

To go to next page by hyperlink propertieso Text nexto Navigate URL default.aspx

When we want to move to next page without submitting the current page we use hyperlink.

Basic Controls in .net

checkbox

checkbox1_checked changed event{

If(checkbox.checked == true){

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 buttono Property GroupName to mention the group.o They have only selected whenever we click on them not lick checkbox.

It’s me - 23 -

Page 24: Chottu Sharma Notes

radiobutton_checked changed event{

Textbox1.forecolor = color.red}

o We must include a namespace to use colorUsing System.Drawing;

Checkbox listo DataBound control it is collection of checkboxeso 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 entryPage_load{

If(page.isPostBack == false){

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

It’s me - 24 -

Page 25: Chottu Sharma Notes

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

}

Textbox propertyTextmode 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;

It’s me - 25 -

Page 26: Chottu Sharma Notes

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.

ADO.Net (ActiveX Data Object)

It is an environment which is design by Microsoft for database handling. Two main components

o XML ( it is lincense free, platform independent and the fastest way of data transfer ).

o Disconnected approach (data is copied at application server and the connect with the database server is disconnected so that original data will remain untouched).

It design while having web application in mind.

Database connectivity

There are 4 ways of connectivity with databaseo ODBC (Open DataBase Connectivity) Used to connect to each n o OLEDB (Object Linking & Embedding) every server

o SQLClient (specifically used with Ms SQL server. It is included in .net)o ORACLEClient (specifically used with Oracle server. It is included in .net)

It’s me - 26 -

Page 27: Chottu Sharma Notes

Better performance and Compatibility

Two main files are thereo .mdf (Microsoft database file)o .ldf ( log database file)

To create databaseo View server explorer o In last there is “server” to know the server nameo Data connection(right click) create new SQL server DBo 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 connectiono Sac.dbemployee table(right click) add new tableo Mention column name and data type as

Eno int Ename varchar(50) Eaddress varchar(50) Esal int

Difference between varchar and nvarchar is that varchar uses ASCII and nvarchar uses Unicode.

Web.config fileo 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 compileo XML based, Case sensitiveo Secure in version 2.0 (we cant view the file without coding)o Intelligence help is provided in version 2.0o 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 etco To add web.config

Website add new item web conf fileo Add connection string in this file

<connection string>

<add name=”nonu” connectionString=”server=sac; database=dbemployee;

keyuid=sa; pwd=admin”/>

It is used if u have

It’s me - 27 -

Page 28: Chottu Sharma Notes

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

// don’t insert control directly on page coz it will not look going when the resolution changes.

It’s me - 28 -

Page 29: Chottu Sharma Notes

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

// Sqldbtype is enumerator(user define datatype) cmd.parameters.add(“@en”,sqldbtype.Varchar, 50).

value = textbox2.text;cmd.executeNonQuery();

// ExecuteNonQuery Execute the query and return the no. of data received.cmd.dispose(); // destructor

textbox1.text= getAuto().toString();//textbox1.text = “ “;textbox2.text = “ “;textbox3.text = “ “;textbox4.text = “ “;

} }}

Update code

Button2_click //update{

SQLcommand cmd = new sqlcommand ();cmd.commandText=”update tbemp set ename=@en, edd =

@ed, esal = @es where empno = @eno”;

It’s me - 29 -

Page 30: Chottu Sharma Notes

cmd.command=con; cmd.parameters.add (“@eno”, sqldbtype.Int).value =

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 = “ “;}Delete Code

Button3_click //delete{

SQLcommand cmd = new sqlcommand(); cmd.commandText=”delete from tbemp where empno=@eno”; cmd.command=con;

cmd.parameters.add(“@eno”,sqldbtype.Int).value =

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;/*

SQLDataReader is used to view data,

It’s me - 30 -

Page 31: Chottu Sharma Notes

It is read only. Forward only ( only go in forward direction) It is the fastest way of data retrieval. Sequential read. No need of “new” operator. It is segantal class used to pass reference just like abstract class. We should close it after using it coz otherwise we can’t use it again like static

method it has only one memory.*/

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)

Listbox1.DataSource = dr;Listbox1.DataBind();

Dr.close();cmd.dispose();

}

Set the autoPostBack property of listbox1 equal to true.

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;

It’s me - 31 -

Page 32: Chottu Sharma Notes

Dr = cmd.ExecuteReader();

If(dr.HasRows){

Dr.Read(); // to read the next lineTextbox1.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();

}

To generate the auto numbers like account no., empno

Private Int32 getAuto(){

SQLcommand cmd = new sqlcommand (); cmd.commandText=”select isNull(max(empno), 0) from

tbemp”;

cmd.connection = con;Int32 r = convert.ToInt32(cmd.executeScalar()) + 1;

// executeScalar for query which return single value, if multiple value is there then It returns first column’s fist value.

cmd.dispose();Return r;

}

It’s me - 32 -

Page 33: Chottu Sharma Notes

STORE PROCEDURES

They can pass maximum 1024 numbers of parameters There are 3 types of parameters

o Input (just to pass the value)o Output (just to return the value)o Input/output (we can pass as well as return value)

They can return value Pre compile objects Difference between function and procedure

o Function must return value, procedure may or may not return valueo Function can return any type of data whether array, integer, object etc but

procedure can return only integer.o Function is used as variable but procedure is executedo Procedure is compiled in memoryo Store in database and executed in database and once execute comes in the

cache which help it run more faster next time.o Store procedure SQL engine par execute hote hai, function first goes to SQL

server and there they first compile n then executed. To create store procedure go to server explorer

o Sac.dbemp (database) Store procedure (Right click) Add new store procedure.

The language in which we work is know as tangent SQL or T-SQL.

Save procedure

CREATE PROCEDURE insemp(

@eno int,@en varchar(50),@ed varchar(50),@es int

)AS

It’s me - 33 -

Page 34: Chottu Sharma Notes

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 don’t 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

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

Select * from tbemp.

Find procedure

CREATE PROCEDURE findemp(

@eno int)AS

Select * from tbemp where empno = @eno

It’s me - 34 -

Page 35: Chottu Sharma Notes

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

Create table (tbuser)o Uname varchar(50)o Upass varchar(50)

CREATE PROCEDURE loginCheck(

@u varchar(50),@p varchar(50)

)AS

Declare @ap varchar(50)SELECT @ap = upass from tbuser where uname = @u

If @ap is nullReturn -1

ElseIf @ap = @p

Return 1Else

Return -2

If we don’t 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;

It’s me - 35 -

Page 36: Chottu Sharma Notes

if (con.state = = connectionState.closed){

Con.open();}

}Private Int32 checkuser(String u, String p){

SQLCommand cmd = new SQLCommand();cmd.commandText = “loginCheck”;cmd.commandType = commandType.StoreProcedurecmd.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”, 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

It’s me - 36 -

Page 37: Chottu Sharma Notes

{Label1.text = ”LOGIN”;

}}

// this is called connected approach coz in this we use “open” to connect

TEMPLATES

Collection of HTML & web controls 8 were included in version 1.1 and in 2.0 two more are added. Total 10 templates are there

o Item templateo Header templateo Footer templateo Select templateo Pager templateo Edit item templateo Separator templateo Alternating item templateo Insert item templateo 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 Repeatoro Data listo Data grid

Five type of Composite databound control are there in version 2.0o Repeatoro Data listo Grid viewo Form viewo Detail view

All Composite databound control work with templates & vice versa

Repeater

To display data in single column No manipulation (data edit, update, delete nahi hota)

It’s me - 37 -

Page 38: Chottu Sharma Notes

No paging No default template We can only apply 5 type of template

o Item templateo Header templateo Footer templateo Separator templateo Insert item template

Repeater disconnected approach o Create a database dbbooko Add a table tbbook

bookId int bookTitle varchar(50) bookAuthor varchar(50) 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 repeatero 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

It’s me - 38 -

Page 39: Chottu Sharma Notes

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

Go to HTML of default.aspx

<asp:Repeater ID="Repeater1" runat="server"> <! Asp Tag Prefix> <! Repeater Tag Name>

<ItemTemplate> <table> <tr> <td width=20px bgcolor=green></td> <td> <img src="<%#Eval("bookImg") %>" width='50px’ height='50px'/> </td> <td> <b>Title: </b><% # Eval("bookTitle")%><br /> <b>Author: </b><% #Eval("bookAuthor")%><br /> <b>Publisher: </b><% #Eval("bookPub")%><br /> <b>Price: </b><% #Eval("bookPrice")%><br /> </td> </tr> </table> </ItemTemplate> </asp:Repeater>

Q. DISPLAY DATA IN TABLE FORM:

Default.aspx<asp:Repeater ID="Repeater1" runat="server"><HeaderTemplate> <table>

It’s me - 39 -

Page 40: Chottu Sharma Notes

<tr bgcolor=green> <th>BookId</th> <th>Title</th> <th>Author</th> <th>Publisher</th> <th>Price</th> <th>Discount</th> <th>Amount</th> </tr></HeaderTemplate>

<ItemTemplate> <tr bgcolor=lime> <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)

It’s me - 40 -

Page 41: Chottu Sharma Notes

{ RepBind();}private void RepBind(){

SqlDataAdapter adp = new SqlDataAdapter("select * from bbook", ConfigurationManager.ConnectionStrings["cs"].ConnectionString);

DataSet ds = new DataSet();

adp.Fill(ds); Repeater1.DataSource = ds; Repeater1.DataBind(); } public Int32 CalDis(Int32 prc) { return prc * 10 / 100; } public Int32 CalAmt(Int32 prc) { return prc - CalDis(prc); }Template

Working and time of all the template are fixed. Order doesn’t disturb the working of templates. In item template

o We define only single row display format.o It will run again n again according to the number of rows.

Header templateo It will run only once for headingo It’s the first template, which will run.

Footer templates will run in the last We can excess only public and protected member in HTML. Alternating item templates work with item templates alternating. Repeater me different column wala concept nahi hota.

Datalist

To display data in multiple column. We can manipulate data (edit, delete, update) No paging. No default template 7 templates are applicable

o Item templateo Header templateo Footer template

It’s me - 41 -

Page 42: Chottu Sharma Notes

o Select templateo Edit item templateo Separator templateo Alternating item template

Q. DISPLAY DATA IN DIFFERENT COLUMN

Place dataList from toolbox Add web config file and make connection string.

Using System.Data.Sqlclient;

Private void ListBind(){

SqlDataAdapter adp = new SqlDataAdapter("select * from tbbook", ConfigurationManager.ConnectionStrings["cs"].ConnectionString);

DataSet ds = new DataSet();

adp.Fill(ds); DataList1.DataSource = ds; DataList1.DataBind(); } Page_load {

If(page.isPostBack==false)ListBind();

}

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>

It’s me - 42 -

Page 43: Chottu Sharma Notes

There are some predefine command nameo Edito Updateo Deleteo Cancelo Selecto New (added in version 2.0, not used with DataList)o Insert (added in version 2.0, not used with DataList)

DataList property RepeatColumn = ValueTo display data in more than one column

To auto format click on DataList Tasks AutoFormat.

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

It’s me - 43 -

Page 44: Chottu Sharma Notes

DataList1_EditCommand(source, e){

DataList1.EditItemIndex = e.Item.ItemIndex;

// e is current selected item

ListBind();}

DataList1_CancelCommand(source, e){

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;

It’s me - 44 -

Page 45: Chottu Sharma Notes

cmd.Parameters.Add("prc", SqlDbType.Int).Value = prc; cmd.Parameters.Add("bid", SqlDbType.Int).Value = bid;

cmd.ExecuteNonQuery(); cmd.Dispose();

DataList1.EditItemIndex = -1; ListBind();

} To make direct connection with database without coding we use SqlDataSource

o It is used with 2 – tier architectureo Two layers in 2 – tier architecture are

Data Access Layer Presentation Layer

o Used for database connectivity, to read, insert, update etc.

Place SqlDataSource from toolbox and click on SqlDataSource tasks Configure Data Source select Database give name to connectionString (mark the checkbox if u want this connection String should added in web.config file) Select table then select columns then click finish. Click on DataList Tasks Choose Data Source SqlDataSource1. To check whether this SqlDataSource is connected or disconnected approach

Click on the properties of SqlDataSource DataSourceMode DataReader(connected approach) / DataSet(disconnected approach)

In HTML

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

It’s me - 45 -

Page 46: Chottu Sharma Notes

<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 /> <asp:LinkButton ID="lb1" Text="Update" CommandName= "update" runat=server></asp:LinkButton>

<asp:LinkButton ID="lb2" text="Cancel" CommandName= "cancel" runat=server></asp:LinkButton><br/><br/>

</EditItemTemplate></asp:DataList>

Go to DataList Property event EditCommand / UpdataCommand / CancelCommand

DataList1_EditCommand(source, e){

DataList1.EditItemIndex = e.Item.ItemIndex; DataList1.DataBind();}DataList1_CancelCommand(source, e){

DataList1.EditItemIndex = -1; DataList1.DataBind();}

SqlDataSource1 Properties UpdateQuery

Update Products set productname=@pn, unitprice=@un, categoryId=@cid, supplierId=@sid where productId=@pid

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

It’s me - 46 -

Page 47: Chottu Sharma Notes

SqlDataSource1.UpdateParameter[“pn”].DefaultValue=pn;SqlDataSource1.UpdateParameter[“un”].DefaultValue=pn;SqlDataSource1.UpdateParameter[“cid”].DefaultValue=cd;SqlDataSource1.UpdateParameter[“sid”].DefaultValue=sd;

/* DataList Property DataKeyField ProductId In this field we mention those field which we don’t want to display but used in

programming. DataKeys Array[0] 0th row ka productId

*/pd = (DataList1.DataKeys[e.item.itemIndex]).ToString();SqlDataSource1.UpdateParameter[“pid”].DefaultValue=pd;SqlDataSource1.update();Datalist1.EditItemIndex = -1;Datalist1.databind();

}

It’s me - 47 -

Page 48: Chottu Sharma Notes

Q. PRODUCTS WITH CHECKBOX

Place DataList1, DataList2, Button Add web.config file.

Using System.Data.Sqlclient;

Page_load {

If(page.isPostBack==false){SqlDataAdapter adp = new SqlDataAdapter("select * from tbbook", ConfigurationManager.ConnectionStrings["cs"].ConnectionString);

DataSet ds = new DataSet(); adp.Fill(ds);

DataList1.DataSource = ds;} DataList1.DataBind();

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

DataSet ds = new DataSet();adp.Fill(ds);

DataList2.DataSource = ds;

It’s me - 48 -

Page 49: Chottu Sharma Notes

DataList2.DataBind();}

In HTML

<asp:DataList1…><ItemTemplate>

<b><%Eval(“productName”)%><br/><asp:checkbox ID=”cb” text=”Buy” runat=server>

</ItemTemplate></asp:DataList1>

<asp:DataList2><ItemTemplate>

<b><%Eval(“productName”)%></b><br/><b><%Eval(“unitPrice”)%></b><br/>

</ItemTemplate></asp:DataList1>

To print output on form we use Response.write(“Hello World”)

It’s me - 49 -

Page 50: Chottu Sharma Notes

Q. DISPLAY SELECTED DATA IN TEXTBOX

Place dataList from toolbox Add web config file and make connection string.

Using System.Data.Sqlclient;

Private void ListBind(){

SqlDataAdapter adp = new SqlDataAdapter("select * from tbbook", ConfigurationManager.ConnectionStrings["cs"].ConnectionString);

DataSet ds = new DataSet();

adp.Fill(ds); DataList1.DataSource = ds; DataList1.DataBind();} Page_load{

If(page.isPostBack==false)ListBind();

}DataList1_SelectedIndexChanged{ String st; st = "select * from tbbook where bookId=" + DataList1.DataKeys[selectedIndex].ToString(); SqlDataAdapter adp = new SqlDataAdapter(st, ConfigurationManager. ConnectionStrings["cs"].ConnectionString); DataSet ds = new DataSet(); adp.Fill(ds); //TextBox1.Text=ds.Tables[0].Rows[0] ["bookTitle"].ToString(); //TextBox2.Text = ds.Tables[0].Rows[0] ["bookAuthor"].ToString();

It’s me - 50 -

Page 51: Chottu Sharma Notes

//TextBox3.Text = ds.Tables[0].Rows[0] ["bookPub"].ToString(); //TextBox4.Text = ds.Tables[0].Rows[0] ["bookPrie"].ToString();

// DS is an object n is very heary so it’s not good to call it again n again. We should use properties, method, variable but not objects

DataRowView r;

// DataRowView class only accept single row.

r=ds.Tables[0].DefaultView[0];

TextBox1.Text = r[0]["bookTitle"].ToString(); TextBox2.Text =r[0]["bookAuthor"].ToString(); TextBox3.Text = r[0]["bookPub"].ToString(); TextBox4.Text = 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>

It’s me - 51 -

Page 52: Chottu Sharma Notes

Q. EXPAND AND COLLAPSE

Place Repeater from toolbox chose data source Place SqlDataSource1 configure data source

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

It’s me - 52 -

Page 53: Chottu Sharma Notes

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

It’s me - 53 -

Page 54: Chottu Sharma Notes

</ItemTemplate> </asp:Repeater>

Div is a container in which we store different things In Style

o Display : none collapse, block expand GetElementById in JavaScript is just like FindControl to find the control.

Q. PAGING

Create a store procedure in database. We use cursor in this which are

o Private area to SQLo Store Result of queryo Information in cursor is called Data set.o The cursor which stores the result of select is called implicit cursor.

Cursor has 4 steps:o Createo Openo Fetcho Close

ALTER PROCEDURE dbo.StoredProcedure1 (

@pagenumber int,@pagesize int

)AS

declare @strec intdeclare @endrec intdeclare @stpid intdeclare @endpid intdeclare @reccount int

set @strec = @pagenumber*@pagesize-@pagesize+1declare c_prd scroll cursor forselect productId from tbproduct order by productId

open c_prdfetch absolute @strec from c_prd into @stpid

// we use absolute coz if value is –ve it take from the last.select @reccount=count(*) from tbproduct where

productid > @stpid

It’s me - 54 -

Page 55: Chottu Sharma Notes

if @reccount < @pagesizebegin

set @endrec = @strec + @reccountendelsebegin

set @endrec = @pagenumber * @pagesizeend

fetch absolute @endrec from c_prd into @endpidclose c_prd

select count(*) from tbproduct

select productName, unitPrice, categoryName from tbproduct a, tbcategory b where a.categoryId = a.categoryId and productId > @stpid and productId <= @endpid

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

It’s me - 55 -

Page 56: Chottu Sharma Notes

cmd.CommandText = "paging"; cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.Add("@pagenumber",SqlDbType.Int).Value=pg;

cmd.Parameters.Add("@pagesize", SqlDbType.Int).Value = nor;

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

It’s me - 56 -

Page 57: Chottu Sharma Notes

Button1.Enabled = true; Button2.Enabled = true; Button3.Enabled = true; Button4.Enabled = true;

if (pg == 1) { 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))

It’s me - 57 -

Page 58: Chottu Sharma Notes

{ if((Convert.ToInt32(Label1.Text))!=(DataList2.Items.Count - 2)) { PageBind(Convert.ToInt32(Label1.Text) + 1); } }

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>

It’s me - 58 -

Page 59: Chottu Sharma Notes

GRIDVIEW

To display data in rows & columns. We can manipulate data (edit, delete, and update). Auto edit, delete, select Inbuilt paging Inbuilt sorting Column bound 8 templates are applicable

o Item templateo Header templateo Footer templateo Select templateo Pager templateo Edit item templateo Alternating item templateo Empty data template

Properties of GridViewo AutoGenerateDeleteButton trueo AutoGenerateEditButton trueo AutoGenerateSelectButton trueo AllowPaging trueo PageSize 2o PagerSetting

Mode Numeric/NextPrevFirstLast FirstPageText First LastPageText Last PrevPageText Prev NextPageText Next Position TopBottom/Bottom

o AllowSorting trueo Columns Bookid properties Readonly trueo DataKeyNames bookid // In DataKeyField we can specify only single value but in DataKeyName we can specify more than 1 using “,”

It’s me - 59 -

Page 60: Chottu Sharma Notes

Properties of SqlDataSourceo UpdateQuery

update tbbook set bookTitle=@bookTitle, bookAuthor=@bookAuthor, bookPub=@bookPub, bookPrice=@bookPrice where bookId=@bookId

// if parameter name is equal to columns name then no need of added parameter to query

o DeleteQuery Delete from tbbook where bookId=@bookId

GridView1_SelectedIndexChanged(sender, e){ TextBox1.Text = GridView1.SelectedRow.Cells[1].Text; TextBox2.Text = GridView1.SelectedRow.Cells[2].Text; TextBox3.Text = GridView1.SelectedRow.Cells[3].Text; TextBox4.Text = GridView1.SelectedRow.Cells[4].Text; TextBox5.Text = GridView1.SelectedRow.Cells[5].Text; }

With Coding

Page_Load(object sender, EventArgs e){

if (Page.IsPostBack == false) { GrdBind(); }}private void GrdBind(){ SqlDataAdapter adp = new SqlDataAdapter("select * from tbbook", ConfigurationManager.ConnectionStrings["cs"].ConnectionString); DataSet ds = new DataSet(); adp.Fill(ds); GridView1.DataSource = ds; GridView1.DataBind();}protected void GridView1_RowEditing(sender, e){ GridView1.EditIndex = e.NewEditIndex; GrdBind();}GridView1_RowCancelingEdit(sender, e){ GridView1.EditIndex = -1; GrdBind();

It’s me - 60 -

Page 61: Chottu Sharma Notes

}GridView1_RowUpdating(sender, e){ SqlConnection con = new SqlConnection(); 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();

It’s me - 61 -

Page 62: Chottu Sharma Notes

cmd.Dispose(); GridView1.EditIndex = -1; GrdBind(); }

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

It’s me - 62 -

Page 63: Chottu Sharma Notes

<ItemTemplate> <%#Eval("bookPub")%> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="tb3" Text='<%#Eval("bookPub")%>' runat="server"> </asp:TextBox> </EditItemTemplate></asp:TemplateField>

<asp:TemplateField HeaderText="Price"> <ItemTemplate> <%#Eval("bookPrice")%> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="tb4" Text='<%#Eval("bookPrice")%>' runat="server"> </asp:TextBox> </EditItemTemplate></asp:TemplateField>

<asp:TemplateField HeaderText="Edit"> <ItemTemplate> <asp:LinkButton ID="lb1" Text="Edit" CommandName="Edit" runat="server"> </asp:LinkButton> </ItemTemplate> <EditItemTemplate> <asp:LinkButton ID="lb3" Text="Update" CommandName="Update" runat="server"> </asp:LinkButton> <asp:LinkButton ID="lb4" Text="Cancel" CommandName="Cancel" runat="server"> </asp:LinkButton> </EditItemTemplate></asp:TemplateField>

<asp:TemplateField HeaderText="Delete"> <ItemTemplate> <asp:LinkButton ID="lb2" Text="Delete" CommandName="Delete" runat="server"> </asp:LinkButton> </ItemTemplate></asp:TemplateField></Columns>

It’s me - 63 -

Page 64: Chottu Sharma Notes

</asp:GridView>

Q. GRID WITHIN GRID

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>&nbsp; <%#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>

It’s me - 64 -

Page 65: Chottu Sharma Notes

</ItemTemplate> </asp:TemplateField> </Columns></asp:GridView>

public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { GrdBind(); } private void GrdBind() { SqlDataAdapter adp = new SqlDataAdapter("select * from tbcategory;select * from tbproduct", ConfigurationManager. ConnectionStrings["cs"].ConnectionString);

DataSet ds = new DataSet(); adp.Fill(ds); GridView1.DataSource = ds; GridView1.DataBind(); } public DataSet GetData(Int32 cid) { String st; st="select * from tbproduct where catergoryId="+cid.ToString(); SqlDataAdapter adp= new SqlDataAdapter(st,ConfigurationManager. ConnectionStrings["cs"].ConnectionString); DataSet ds = new DataSet(); return (ds); }}

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)

It’s me - 65 -

Page 66: Chottu Sharma Notes

{ GrdBind(); } private void GrdBind() { SqlDataAdapter adp = new SqlDataAdapter("select * from tbcategory;select * from tbproduct", ConfigurationManager. ConnectionStrings["cs"].ConnectionString); 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; }}

It’s me - 66 -

Page 67: Chottu Sharma Notes

Q. GRAND AND SUBTOTAL

using System.Data.SqlClient;using System.Drawing;

public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { GrdBind(); } private void GrdBind() { String st; st = "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 a, categories b where a.categoryId=b.categoryId group by categoryname, productname with rollup"; SqlDataAdapter adp=new SqlDataAdapter(st,ConfigurationManager. ConnectionStrings["cs"].ConnectionString);

DataSet ds = new DataSet(); adp.Fill(ds); Int32 i=0; String pc = ""; String nc = ""; while (i < ds.Tables[0].Rows.Count-1) { nc = ds.Tables[0].Rows[i][0].ToString(); if (nc != pc) {

It’s me - 67 -

Page 68: Chottu Sharma Notes

pc = nc; DataRow r; r = ds.Tables[0].NewRow(); 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; }

}}

It’s me - 68 -

Page 69: Chottu Sharma Notes

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

It’s me - 69 -

Page 70: Chottu Sharma Notes

Q. ADD ITEMS IN TABLE

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() { SqlDataAdapter adp = new SqlDataAdapter("select * from tbemp", ConfigurationManager.ConnectionStrings["cs"].ConnectionString); DataSet ds = new DataSet(); adp.Fill(ds); GridView1.DataSource = ds; GridView1.DataBind();

It’s me - 70 -

Page 71: Chottu Sharma Notes

} protected void GridView1_RowCommand(sender, e) { 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.CommandText = "select isNull(max(empno), 0) from tbemp";

It’s me - 71 -

Page 72: Chottu Sharma Notes

cmd.Connection = con;

Int32 r = Convert.ToInt32(cmd.ExecuteScalar())+ 1; 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;

It’s me - 72 -

Page 73: Chottu Sharma Notes

if (con.State == ConnectionState.Closed) { con.ConnectionString = ConfigurationManager. ConnectionStrings["cs"].ConnectionString; con.Open(); } SqlCommand cmd = new SqlCommand(); cmd.CommandText = "update tbemp set ename=@en, eaddress=@eadd, esal=@es where empno=@eno";

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(); cmd.Dispose(); GridView1.EditIndex = -1; GrdBind(); } protected void GridView1_RowCancelingEdit(sender, e) { GridView1.EditIndex = -1; GrdBind(); }}

It’s me - 73 -

Page 74: Chottu Sharma Notes

Q. TO DISPLAY DATA IN TEXTBOX JUST CLICKING ON ROW

Place Gridview chose data source Place SQLDataSource and configure it. GridView (properties)ColumnsCommandFieldadd Selectproperties Visible = false

protected void GridView1_RowDataBound(sender, e){ if (e.Row.RowType == DataControlRowType.Header) { } else if (e.Row.RowType == DataControlRowType.Footer) { } else { 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;}

It’s me - 74 -

Page 75: Chottu Sharma Notes

In HTML

<%@ Page Language="C#" EnableEventValidation="false"...%>

Q. TO SELECT COLUMNS TO BE DISPLAY AT RUN TIME

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()); // to get the value of that column we can use GetValue } } } protected void Button1_Click(sender, EventArgs e) { String st = "";

It’s me - 75 -

Page 76: Chottu Sharma Notes

Int32 i; for (i = 0; i < CheckBoxList1.Items.Count; i++) { 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); DataSet ds = new DataSet(); adp.Fill(ds); GridView1.DataSource = ds; GridView1.DataBind(); }}

It’s me - 76 -

Page 77: Chottu Sharma Notes

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 Edito Updateo Cancelo Deleteo Newo Insert

We use Detail view for single record operation . Place DetailView, SqlDataSource and configure them Properties of DetailView

o AutoGenerateDeleteButton trueo AutoGenerateEditButton trueo AutoGenerateInsertButton trueo AllowPaging trueo DataKeyNames bookid

Properties of SqlDataSourceo 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)

It’s me - 77 -

Page 78: Chottu Sharma Notes

If parameter name are different from columns name

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

It’s me - 78 -

Page 79: Chottu Sharma Notes

DETAIL VEIW WITH CODING

Place DetailVeiw Add Web Config File DetailVeiw properties AutoGenrateRows false DetailVeiw properties fields Add template fields

o Empnoo Nameo Addresso Salaryo For buttons

DetailVeiw Tasks Edit Templateso Empno

ItemTempLabelEditDataBinding codeEval(“empno”) EditItemTemLabelEditDataBinding codeEval(“empno”) InsertItemTextboxEditDataBinding codeEval(“empno”)

o Ename ItemTempLabelEditDataBinding codeEval(“ename”) EditItemTemTextboxEditDataBindincodeEval(“ename”) InsertItemTextboxEditDataBinding codeEval(“ename”)

o Eaddress ItemTempLabelEditDataBinding codeEval(“eadd”) EditItemTemTextBoxEditDataBinding

codeEval(“eadd”) InsertItemTextboxEditDataBinding codeEval(“eadd”)

o Esal ItemTempLabelEditDataBinding codeEval(“esal”) EditItemTemTextboxEditDataBinding codeEval(“esal”) InsertItemTextboxEditDataBinding codeEval(“esal”)

o Buttons ItemTemp LinkButtons

It’s me - 79 -

Page 80: Chottu Sharma Notes

Edit (CommandName edit)New (CommandName new)Delete(CommandName delete)

EditItemTemTextboxEditDataBinding codeEval(“esal”)Update (CommandName update)Cancel (CommandName Cancel)

InsertItemTextboxEditDataBinding codeEval(“esal”)Save (CommandName Insert)Cancel (CommandName Cancel)

o 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); DataSet ds = new DataSet(); adp.Fill(ds); DetailsView1.DataSource = ds; DetailsView1.DataBind(); } protected void DetailsView1_ModeChanging(sender, e) { if (e.NewMode == DetailsViewMode.Edit) { DetailsView1.ChangeMode(DetailsViewMode.Edit); // for EditItemTemplate } else if (e.NewMode == DetailsViewMode.Insert) { DetailsView1.ChangeMode(DetailsViewMode.Insert); // for InsertItemTemplate

It’s me - 80 -

Page 81: Chottu Sharma Notes

} else { DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);

// for ItemTemplate } DetailBind(); }

protected void DetailsView1_ItemDeleting(sender, e){ Int32 eno; eno = Convert.ToInt32(((Label)(DetailsView1. Rows[0].FindControl("label1"))).Text); SqlConnection con = new SqlConnection(); 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(); DetailBind();}protected void DetailsView1_ItemInserting(Sender, e){ Int32 eno, es; String en, ed; eno = Convert.ToInt32(((TextBox)(DetailsView1. Rows[0].FindControl("textbox1"))).Text); en = ((TextBox)(DetailsView1.Rows[1]. FindControl("textbox3"))).Text;

ed = ((TextBox)(DetailsView1.Rows[2].

It’s me - 81 -

Page 82: Chottu Sharma Notes

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

It’s me - 82 -

Page 83: Chottu Sharma Notes

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(); }}Q. TO SELECT PRODUCT TO SEE THE DETAILS

Place Drop Down List o choose data source SqlDataSource1o Enable PostBack

Place Grid Viewo choose data source SqlDataSource2o Enable Select button

Place Detail Viewo choose data source SqlDataSource3

Add SqlDataSource1o In “NorthWind” database chose “categories” table in which select

“categoryId”, “categoryName” columns Add SqlDataSource2

o In “NorthWind” database chose “Product” table in which select “ProductId”, “ProductName”,”UnitPrice” columns

o Click on where button set Column CategoryId

Operator = Source Control

ControlId DropDownListo Click on add button

Add SqlDataSource3o In “NorthWind” database chose “Product” table in which select “*”

columnso Click on where button set Column ProductId

Operator = Source Control

It’s me - 83 -

Page 84: Chottu Sharma Notes

ControlId GridViewo Click on add button

Q. TO SELECT PRODUCT TO PURCHASE AND CHECK DETAIL

Place Drop Down List Place GridView1 Place GridView2 Place LinkButtons (Show List, Add items to List, Select All, Deselect All)

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 Categories"; cmd.Connection = con; SqlDataReader dr;

It’s me - 84 -

Page 85: Chottu Sharma Notes

dr = cmd.ExecuteReader(); DropDownList1.DataTextField = "CategoryName"; DropDownList1.DataValueField = "CategoryId"; DropDownList1.DataSource = dr; DropDownList1.DataBind(); dr.Close(); cmd.Dispose(); } private void GrdBind() { String st = "Select * from Products a,Suppliers b where a.SupplierId=b.SupplierId and CategoryId=" + DropDownList1.SelectedValue.ToString(); SqlDataAdapter adp=new SqlDataAdapter(st, ConfigurationManager.ConnectionStrings["cs"]. ConnectionString); DataSet ds = new DataSet(); adp.Fill(ds); GridView1.DataSource=ds; GridView1.DataBind(); } DropDownList1_SelectedIndexChanged( sender, e) { GrdBind(); } protected void LinkButton4_Click(sender, e) { this.SmartNavigation = true; Int32 i; for (i = 0; i < GridView1.Rows.Count; i++) { CheckBox cb = (CheckBox)(GridView1.Rows[i]. FindControl("cb")); cb.Checked = true; } } protected void LinkButton3_Click(sender, e) { this.SmartNavigation = true; Int32 i; for (i = 0; i < GridView1.Rows.Count; i++) { CheckBox cb = (CheckBox)(GridView1.Rows[i]. FindControl("cb")); cb.Checked = false; }

It’s me - 85 -

Page 86: Chottu Sharma Notes

} 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); DataSet ds = new DataSet(); adp.Fill(ds); GridView2.DataSource = ds;

It’s me - 86 -

Page 87: Chottu Sharma Notes

GridView2.DataBind(); } protected void GridView2_RowCommand(sender, e) { if (e.CommandName == "Buy") { SqlConnection con1 = new SqlConnection(); con1.ConnectionString = ConfigurationManager. ConnectionStrings["cs1"].ConnectionString; 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'; } } for(var i=0;i<12;i++)

It’s me - 87 -

Page 88: Chottu Sharma Notes

{ 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= "DropDownList1_SelectedIndexChanged" ></asp:DropDownList><br /><asp:GridView ID="GridView1" runat="server" Width="693px"

It’s me - 88 -

Page 89: Chottu Sharma Notes

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>&nbsp;&nbsp;&nbsp;<%#Eval("city")%><br /><b>Phone:</b>&nbsp;&nbsp;&nbsp;<%#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><asp:Label ID="l2" Text='<%#Eval("UnitPrice")%>' runat="server"></asp:Label> </ItemTemplate>

It’s me - 89 -

Page 90: Chottu Sharma Notes

</asp:TemplateField>

<asp:TemplateField HeaderText="Stock"><ItemTemplate> <%#Eval("UnitsInStock")%></ItemTemplate></asp:TemplateField></Columns></asp:GridView>

<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"><Columns><asp:BoundField HeaderText="Product Name" DataField="ProductName" /><asp:BoundField HeaderText="Price" DataField="Price" /><asp:TemplateField><FooterTemplate><asp:LinkButton ID="LinkButton5" runat="server" CommandName="Buy">Buy</asp:LinkButton></FooterTemplate></asp:TemplateField></Columns></asp:GridView></div></form></body></HTML>

It’s me - 90 -

Page 91: Chottu Sharma Notes

FORMVIEW

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 Edito Updateo Cancelo Deleteo Newo 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)

EditItemTemplateo Write Empno, place LabelEditDataBinding codeEval(“empno”)

It’s me - 91 -

Page 92: Chottu Sharma Notes

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)

InsertItemTemplateo 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 availableo Write No Data Availableo 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() { SqlDataAdapter adp = new SqlDataAdapter("select * from tbemp", ConfigurationManager.ConnectionStrings["cs"].ConnectionString); DataSet ds = new DataSet(); adp.Fill(ds); FormVeiw1.DataSource = ds; FormView1.DataBind(); } protected void FormView1_ModeChanging(sender, e) { if (e.NewMode == FormViewMode.Edit) { FormView1.ChangeMode(FormViewMode.Edit); // for EditItemTemplate

It’s me - 92 -

Page 93: Chottu Sharma Notes

} 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); SqlConnection con = new SqlConnection(); 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(); FormBind();}protected void FormView1_ItemInserting(Sender, e){ Int32 eno, es; String en, ed; eno = Convert.ToInt32(((TextBox)(FormView1. FindControl("textbox4"))).Text); en= ((TextBox)(FormView1.FindControl("textbox5"))).Text;

ed= ((TextBox)(FormView1.FindControl("textbox6"))).Text;

It’s me - 93 -

Page 94: Chottu Sharma Notes

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, eaddress=@ed,esal=@es where empno=@eno";

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;

It’s me - 94 -

Page 95: Chottu Sharma Notes

cmd.ExecuteNonQuery(); cmd.Dispose(); FormView1.ChangeMode(FormViewMode.ReadOnly); FormBind(); }

protected void FormView1_PageIndexChanging(sender, e) { FormView1.PageIndex = e.NewPageIndex; FormBind(); }}

CLASSES

Collection of similar type of data Objects can use each n every members Types:

Non compiled classeso Compile with projecto Scope within the project

Website Add new items class

Imports System.DataImports System.Data.SqlClientImports 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 adp.Fill(ds) obj.DataTextField = datatext obj.DataValueField = datavalue obj.DataSource = ds obj.DataBind() End Sub End Class

It’s me - 95 -

Page 96: Chottu Sharma Notes

Public Class clsEmp Public eno As Int32 Public en As String Public eadd As String Public es As Int32‘ we don’t 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 End Set End Property Public Property p_ename() As String Get Return en End Get

It’s me - 96 -

Page 97: Chottu Sharma Notes

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

Public Property p_esal() As Int32 Get Return es End Get Set(ByVal value As Int32) es = value End Set End Property Public Function disp() As String Return "Empno: " & p_empno & "EName: " & p_ename & " Address: " & p_eadd & "Esal: " & p_esal End Function End Class Public Class clsEmp2 Shared ctr As Int32 ‘ Shared = Static Public Sub New() ctr += 1 End Sub Public ReadOnly Property p_ctr() As Int32 Get Return ctr End Get End Property End ClassEnd Namespace

Place textbox Place three buttons Place DropDownList

It’s me - 97 -

Page 98: Chottu Sharma Notes

Partial Class _Default Inherits System.Web.UI.Page

Button1_Click() Handles Button1.Click Dim obj As New nsEmp.clsEmp obj.eno = 66 obj.en = " sachin gupta" obj.eadd = "Ramnagar" obj.es = 23007 TextBox1.Text = obj.disp() End Sub

Button2_Click() Handles Button2.Click Dim obj As New nsEmp.clsEmp1 obj.p_empno = 66 obj.p_ename = " sachin gupta" obj.p_eadd = "16-17 Ramnagar" obj.p_esal = 23007 TextBox1.Text = obj.disp() End Sub

Button3_Click() Handles Button3.Click Dim obj As New nsEmp.clsEmp2 TextBox1.Text = obj.p_ctr 'obj.p_ctr = 111 error End Sub

Page_Load() Handles Me.Load nsEmp.clscomfuntion.Fill_Data("Select * from bemp", DropDownList1, "ename", "empno") End SubEnd Class

It’s me - 98 -

Page 99: Chottu Sharma Notes

OVERLOADING AND OVERRIDING

Namespace nsemp Public MustInherit Class clsemp 'MustInherit is same as abstact Protected esal As Int32 Public Sub New() esal = 20000 End Sub

'overriding always use with inheritance 'same signature of override method 'there is single copy of method

Public Overridable Function CalAlw() As Int32 Return esal * 10 / 100 End Function Public MustOverride Property p_sal() As Int32'MustOverRide only declare in abstact class and the class which inherit this must ‘ override this method Public Function Shadow(ByVal pf As Int32) As Int32 Return esal * pf / 100 End Function End Class

Public Class clsgenemp Inherits clsemp

Public Overrides Property p_sal() As Integer

It’s me - 99 -

Page 100: Chottu Sharma Notes

Get Return MyBase.esal End Get Set(ByVal value As Integer) MyBase.esal = value End Set End Property End Class

Public Class clsvipemp Inherits clsemp

Public Overrides Function CalAlw() As Integer Return MyBase.esal * 20 / 100 End Function ' myBase refer to base class and in c# we use Base keyword

Public Overrides Property p_sal() As Integer Get Return MyBase.esal End Get Set(ByVal value As Integer) MyBase.esal = value End Set End Property Public Shadows Function shadow(ByVal pf As Int32, ByVal tax As Int32) As Int32 Return MyBase.esal * pf / 100 + MyBase.esal * tax / 100 End Function

Public Shadows Function shadow(ByVal pf As Int32, ByVal tax As Int32, ByVal loan As Int32) As Int32

Return MyBase.esal * pf / 100 + MyBase.esal * tax / 100 + MyBase.esal * loan / 100 End Function End Class

Public Class clscust Inherits clsemp Public Shadows shadow As Int32 Public Overrides Property p_sal() As Integer Get

End Get Set(ByVal value As Integer)

It’s me - 100 -

Page 101: Chottu Sharma Notes

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

DATABASE HANDLING WITH CLASS (VB.Net)

Add Webconfig file Add a class file Place 4 textboxs Place 4 button and a listbox AutoPostBack true

Imports System.Data.SqlClientImports System.DataImports 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 Property p_esal() As String End Interface Public MustInherit Class clscon Protected con As New SqlConnection Public Sub New() con.ConnectionString = ConfigurationManager. ConnectionStrings("cs").ConnectionString End Sub

It’s me - 101 -

Page 102: Chottu Sharma Notes

End Class

Public Class clsemp Inherits clscon Implements intcom, intemp 'phele class inherit then implement interface

Private eno As Int32 Private en As String Private ed As String Private es As Int32

Public Sub Delete_Rec() If con.State = ConnectionState.Closed Then con.Open() End If Dim cmd As New SqlCommand("delemp", con) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@eno",SqlDbType.Int).Value = p_empno cmd.ExecuteNonQuery() cmd.Dispose() con.Close() End Sub

Public Function Find_rec() As System.Data.DataSet ‘it will open connection and after use close it Dim adp As New SqlDataAdapter("findemp", con) adp.SelectCommand.Parameters.Add("@eno", SqlDbType.Int).Value = p_empno adp.SelectCommand.CommandType = CommandType. StoredProcedure Dim ds As New DataSet() adp.Fill(ds) 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)

It’s me - 102 -

Page 103: Chottu Sharma Notes

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

Public Sub Update_Rec() If con.State = ConnectionState.Closed Then con.Open() End If Dim cmd As New SqlCommand("updemp", 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

Public Property p_eadd() As String Get Return ed End Get Set(ByVal value As String) ed = value End Set End Property

Public Property p_empno() As Integer Get Return eno

It’s me - 103 -

Page 104: Chottu Sharma Notes

End Get Set(ByVal value As Integer) eno = value 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_esal() As String Get Return es End Get Set(ByVal value As String) es = value End Set End Property End Class

Public Class comfunction 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=dbemployee;uid=sa") Dim ds As New DataSet adp.Fill(ds) obj.DataTextField = datatext obj.DataValueField = datavalue obj.DataSource = ds obj.DataBind() End Sub End ClassEnd Namespace

In Default.aspx.cs

Imports System.Data

Partial Class _Default

It’s me - 104 -

Page 105: Chottu Sharma Notes

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 nsemp.comfunction.Fill_Data("select * from tbemp", ListBox1, "ename", "empno") End Sub

Protected Sub ListBox1_SelectedIndexChanged() obj.p_empno = Convert.ToInt32(ListBox1.SelectedIndex) Dim ds As New DataSet() ds = obj.Find_rec()

It’s me - 105 -

Page 106: Chottu Sharma Notes

Dim r As DataRowView r = ds.Tables(0).DefaultView(0) TextBox1.Text = r(0).ToString() TextBox2.Text = r(1).ToString() TextBox3.Text = r(2).ToString() TextBox4.Text = r(4).ToString() End SubEnd Class

DATABASE HANDLING WITH CLASS (C#.Net)

Add Webconfig file and a class file Place 4 textboxs , 4 button and a listbox AutoPostBack true

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; } Int32 p_sal { get; set; } String p_ename { get;

It’s me - 106 -

Page 107: Chottu Sharma Notes

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

public int p_sal { get { return es; } set {

It’s me - 107 -

Page 108: Chottu Sharma Notes

es = value; } }

public string p_ename { get { return en; } set { en = value; } }

public string p_eadd { get { return ed; } set { ed = value; } }

#endregion

#region intcom Members

public void Save_Rec() { 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_empno; cmd.Parameters.Add("@en", SqlDbType.VarChar, 50).Value = p_ename; cmd.Parameters.Add("@ed", SqlDbType.VarChar, 50).Value = p_eadd;

It’s me - 108 -

Page 109: Chottu Sharma Notes

cmd.Parameters.Add("@es", SqlDbType.Int).Value = p_sal; cmd.ExecuteNonQuery(); cmd.Dispose(); con.Close(); }

public void Update_Rec() { 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_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_sal; cmd.ExecuteNonQuery(); cmd.Dispose(); con.Close(); }

public void Delete_Rec() { 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_empno; cmd.ExecuteNonQuery(); cmd.Dispose(); con.Close(); }

public DataSet Find_rec() { SqlDataAdapter adp = new SqlDataAdapter("findemp", con);

It’s me - 109 -

Page 110: Chottu Sharma Notes

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); DataSet ds = new DataSet(); adp.Fill(ds); obj.DataTextField = datatext; obj.DataValueField = datavalue; obj.DataSource = ds; obj.DataBind(); } }}

In Default.aspx.cs

public partial class _Default : System.Web.UI.Page { nsemp.clsemp obj = new nsemp.clsemp(); protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click() { 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.Save_Rec(); TextBox1.Text = ""; TextBox2.Text = ""; TextBox3.Text = ""; TextBox4.Text = ""; }

It’s me - 110 -

Page 111: Chottu Sharma Notes

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

It’s me - 111 -

Page 112: Chottu Sharma Notes

DATABASE HANDLING USING CUSTOM COLLECTION

Add Webconfig file and a class file

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;

It’s me - 112 -

Page 113: Chottu Sharma Notes

} } 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; } set { en = value; } }

public string p_eadd

It’s me - 113 -

Page 114: Chottu Sharma Notes

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

It’s me - 114 -

Page 115: Chottu Sharma Notes

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

It’s me - 115 -

Page 116: Chottu Sharma Notes

{ 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(); con.Close(); return obj; } }}

Place formviewDataKeyNames p_empno

It’s me - 116 -

Page 117: Chottu Sharma Notes

Choose Data source object data source1Enable Paging true

Place object data source1 Used with 3 tier architecture Stateless ( after doing it’s 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_empnoChoose Data source object data sourceEnable 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

It’s me - 117 -

Page 118: Chottu Sharma Notes

DLL (Dynamic link library)

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;

It’s me - 118 -

Page 119: Chottu Sharma Notes

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

public int p_esal { get { return es; } set { es = value; } } public string p_ename { get

It’s me - 119 -

Page 120: Chottu Sharma Notes

{ return en; } 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,

It’s me - 120 -

Page 121: Chottu Sharma Notes

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

It’s me - 121 -

Page 122: Chottu Sharma Notes

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

It’s me - 122 -

Page 123: Chottu Sharma Notes

cmd.Dispose(); con.Close(); return obj; } }}

Built built class library If DLL is in C# or Vb & front in opposite language then that is called COM

interportability Path classlibrary1/classlibrary1/Bin/Debug To add a DLL file website add reference browse

DATABASE HANDLING USING DLL FILE

Place 4 textbox, 4 buttons , one listbox Add DLL file Place Object data source configure clsemp select disp_rec() Bind it with listbox, enable post back true

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

It’s me - 123 -

Page 124: Chottu Sharma Notes

{ 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 = ""; TextBox1.Focus(); } protected void ListBox1_SelectedIndexChanged(object, e) { List<nsemp.clsempprp> k; k = obj.find_rec(Convert.ToInt32(ListBox1.SelectedIndex)); TextBox1.Text = k[0].p_empno.ToString(); TextBox2.Text = k[0].p_ename; TextBox3.Text = k[0].p_eadd; TextBox4.Text = k[0].p_esal.ToString(); }}

It’s me - 124 -

Page 125: Chottu Sharma Notes

MASTER PAGES

For common layout on all the pages. In 1.1 there was no master pages concept we use web user control but in this at

every page code copy hota hai. In 2.0 there is two pages Master Page(design), content page(HTML) and they

combine at run time to make one page. To insert master page website Add new item Master page Extension of master page is *.master Ek page par ek se jada master page ho sakte hai Layout Insert table Template header,footer&Side Add picture in project and drag it on header Jahan design fix nahi karma Add Content Place Holder Master Page Run Nahi hota we should add Content page Add Adrotator tool to rotate the images when we click refresh To bind images in Adrotater add XML file or table in database Adrotator properties AdvertisementFile XML File KeywordFilter Top / bottom

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>

It’s me - 125 -

Page 126: Chottu Sharma Notes

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

Add Label on master page To excess this label in Content page

public partial class Default2 : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { Label lb = (Label)(Master.FindControl("label1")); lb.Text = "Page2"; }}

To excess properties made master page, in Content page First Made content page strong type by adding following line in source

<%@ MasterType VirtualPath ="~/MasterPage.master"%>

Master Page

using System.Drawing;public partial class MasterPage : System.Web.UI.MasterPage

It’s me - 126 -

Page 127: Chottu Sharma Notes

{ public Color p_fcolor { get { return Label1.ForeColor; } set { Label1.ForeColor = value; } }}Content Page

using System.Drawing;protected void Page_Load(object sender, EventArgs e){ Master.p_fcolor = Color.Red;}

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

Add it from WebsiteAdd new items SiteMap

<?xml version="1.0" encoding="utf-8" ?><siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap- File-1.0" > <siteMapNode url="" title="Menu" description="Menu"> <siteMapNode url="default2.aspx" title="Page1" description="Page1" /> <siteMapNode url="default3.aspx" title="Page2" description="Page2" /> <siteMapNode url="" title="Sub Menu" description="Sub menu"> <siteMapNode url="default4.aspx" title="page3"></siteMapNode> <siteMapNode url="default5.aspx" title="Page4"></siteMapNode>

It’s me - 127 -

Page 128: Chottu Sharma Notes

</siteMapNode> </siteMapNode></siteMap>

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

It’s me - 128 -

Page 129: Chottu Sharma Notes

TO UPLOAD FILE ON SERVER

From toolbox FileUpload Place a button (upload)

protected void Button1_Click(object sender, EventArgs e) { String st = FileUpload1.PostedFile.FileName;

// file path at client machine

Int32 i = st.LastIndexOf("\\");

// "\" used with excape sequences that's y we use "\\"

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

}

It’s me - 129 -

Page 130: Chottu Sharma Notes

TO STORE IMAGE IN DATABASE IN BINARY FORM

Create a table tbimage imageId int imgName image ext varchar(50) Add Web config file Place textbox for id Place Fileupload tool and a button

using System.Data.SqlClient;using System.IO;

public partial class _Default : System.Web.UI.Page { protected void Button1_Click(object sender,EventArgs e) { Int32 ln; ln = FileUpload1.PostedFile.ContentLength; Byte[] ar = new byte[ln]; FileStream fs = new FileStream(FileUpload1.PostedFile.FileName, FileMode.Open, FileAccess.Read);

// FileStream is used to read/write data in binary format

fs.Read(ar, 0, ln - 1); fs.Close(); String fn; fn = FileUpload1.PostedFile.FileName; String ext; ext = fn.Substring(fn.LastIndexOf("."));

// lastIndexOf starts Searching from right hand side

It’s me - 130 -

Page 131: Chottu Sharma Notes

SqlConnection con = new SqlConnection(); con.ConnectionString = ConfigurationManager. ConnectionStrings["cs"].ConnectionString; con.Open(); SqlCommand cmd = new SqlCommand(); cmd.CommandText = "insert into tbimage values(@id, @name, @ext)"; cmd.Connection = con; cmd.Parameters.Add("@id", SqlDbType.Int).Value = Convert.ToInt32(TextBox1.Text);

cmd.Parameters.Add("@name", SqlDbType.Image).Value = ar; cmd.Parameters.Add("@ext", SqlDbType.VarChar, 50).Value = ext; cmd.ExecuteNonQuery(); cmd.Dispose(); con.Close();

}

To retrieve it

Place textbox for id Place Image tool and a button

protected void Button2_Click(object sender, EventArgs e){ SqlConnection con = new SqlConnection(); con.ConnectionString = ConfigurationManager. ConnectionStrings["cs"].ConnectionString; con.Open(); SqlCommand cmd = new SqlCommand(); cmd.CommandText = "select * from tbimage where imageId=@id"; cmd.Connection = con; cmd.Parameters.Add("@id", SqlDbType.Int).Value = Convert.ToInt32(TextBox2.Text); SqlDataReader dr; dr = cmd.ExecuteReader(); if (dr.HasRows) { dr.Read(); Byte[] ar = (Byte[])(dr[1]);

It’s me - 131 -

Page 132: Chottu Sharma Notes

// in dr[0] id, dr[1] image in binary, dr[2] extension

String fn; String a; a = Guid.NewGuid().ToString();

//Guid Global unique identifier;

fn = Server.MapPath(a + dr[2].ToString()); FileStream fs = new FileStream(fn, FileMode.Create, FileAccess.Write); fs.Write(ar, 0, ar.Length - 1); fs.Close(); Image1.ImageUrl = fn; } dr.Close(); cmd.Dispose(); con.Close(); }

To remove files

protected void Button3_Click(object sender, EventArgs e){ DirectoryInfo dir = new DirectoryInfo(Server.MapPath("."));

//"." --> Current folder otherwise folder name FileInfo fi = dir.GetFiles("*.gif”); foreach(FileInfo f in fi) { fi.Delete(f.FullName); }

}

It’s me - 132 -

Page 133: Chottu Sharma Notes

TEMPORARY TABLES

No insert, update, select, delete query They are on client side only. If conform, we can add them in Database. It is just like 2D array. But formatted like tables in db We can make primary key, foreign key, expression columns

Place a GridView

protected void Page_Load(object sender, EventArgs e){ 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",

It’s me - 133 -

Page 134: Chottu Sharma Notes

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

It’s me - 134 -

Page 135: Chottu Sharma Notes

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

It’s me - 135 -

Page 136: Chottu Sharma Notes

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

}

It’s me - 136 -

Page 137: Chottu Sharma Notes

ASSEMBLIES

DLL is known as Assembly in .Net Coz DLL is Specific to CLR. Assemblies are logic units, Data Structure It is just an information required at run time to execute an application Manifest contain information about Assemblies Manifest is a group of Metadata tables Metadata tables are of two types

Custom Assembly (which we create) Predefine

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.

To create Share file

Start All Programs Ms Visual Studio 2005 Visual Studio tools Visual Studio Command Prompt

It’s me - 137 -

Page 138: Chottu Sharma Notes

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 projectWebsite Add reference browse classLibrary1 obj debug DLL file 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

To create Satellite Assembly

To check the language of browserInternet Explorer tools Internet options languagesCodesEnglish ------ en-usFrench ------- fr-beGerman ------ de-at

In new website add new text fileWebsite add new items text file

File name abc.en-us.txt //Where abc is base name, en is culture, us is region Add one more text file File name abc.fr-be.txt Add one more text file

File name abc.de-at.txt In TextFile abc.en-us.txt

A = WelcomeB = English

It’s me - 138 -

Page 139: Chottu Sharma Notes

C = LanguageD = US

In TextFile abc.fr-be.txtA = hbjgjB = FrenchC = gchghgcvD = hvjvjhy

In TextFile abc.de-at.txtA = hbbkjbckdB = GermanC = gycdakcbD = chdihcdn

To convert text file into resource file goto command prompt of .NetC:\website\resgen abc.en-us.txt abc.en-us.resourcesC:\website\resgen abc.fr-be.txt abc.fr-be.resourcesC:\website\resgen abc.de-at.txt abc.de-at.resources

In a resource file o we can store

Bit map Icons Common messages

o They are compiledo Compressed data

In page place DropDownListo Edit Items

Text EnglishValue en-us

Text FrenchValue fr-be

Text GermanValue de-at

Add Global Application classo Global.asaxo Ek project me ek hi ho sati haio To manage application ans session events

<%@ Import Namespace="System.Resources" %><%@ Import Namespace="System.Threading" %><%@ Import Namespace="System.Globalization" %>

<script runat="server">

void Application_Start(object sender, EventArgs e) {

It’s me - 139 -

Page 140: Chottu Sharma Notes

// Code that runs on application startup // yeh cod ek hi baar fire hota hai Application["ab"] = ResourceManager. CreateFileBasedResourceManager ("abc", Server.MapPath("."), null);

// application varible(Global, used by all files) // yeh wohi resources file uthaiga jiska base name "abc" hoga

}

// select BeginRequest event of Applicationprotected void Application_BeginRequest(object, EventArgs){ // 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 browserusing 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) {

It’s me - 140 -

Page 141: Chottu Sharma Notes

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"); } protected void DropDownList1_SelectedIndexChanged() { SetCul(DropDownList1.SelectedValue); }}

It’s me - 141 -

Page 142: Chottu Sharma Notes

State Management

Common in all web development language like PHP, .net, java. 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 managemento Cookieso View stateo Query stringo Hidden fieldso Control state (in Asp.Net 2.0 only)

4 technology included in server side state managemento Sessionso Applicationo Profile (in Asp.Net 2.0 only)o Cache

To check there performance we check three things according to our requiremento Storing capacity

It’s me - 142 -

Page 143: Chottu Sharma Notes

o Type of informationo Scope

Client Side State Management

Cookies o It is a small text file created on client’s machine which is used to store text as

well as number.(we can store only string value not objects)o Two types of cookies

Impersistence cookies (temporary) These are destroyed as soon as browser is closed

Persistence Which expire after a specific time specified by programmer.

o Cookies store Impersistence cookies in browser memory Persistence cookies in cookies folder

(Document & settingusernamecookies)o It can store 4096 bytes (4kb) of data internet explorer but dependent on

browser or on version.o Initial size of a cookie is 50 bytes (In which expiry date/time is store)o We can restrict cookies according to patho Cookies are URL specific which means yahoo wali gmail per use nahi hogi.o A web site can create maximum 20 cookieso Cookies expiry date/time is of server not of client.o A cookie can store information in form of key value pairs.o It is used when we want to store more than one information in a cookie but we

should manage it properly with key value.o Disadvantage

Clients can disable on his/her cookies files. So it is not reliable which means we are not sure that it will run on

client machine or not. Size limitation User can manipulate Some browsers don’t support cookies.

o Scope Though out the website, on all the pages of website.

o Working On every request cookies goes to server where there expiry date/time

is checked entries of cookies expire then text file is also deleted Subkey

No initial space Attach with cookie

It’s me - 143 -

Page 144: Chottu Sharma Notes

There is no expiry date/time, destroy with cookie only NamevalueCollection class is used to read subkey value To read subkey name we use AllKeys (array of keys)

View State (included in .net only)

o Every webpage contain a hidden field name as “_ _viewstate” which is provided by Microsoft.

o “_ _ViewState store information as multiple key pairs (as array)o It stores information in hasted (it helps in data retrieving faster), compressed

form and encoded.o Every web server control has property

enableViewState (by default it is true) when it is true control before posting to server store there information in _ _viewState

o viewState variable can store text, number as well as object.o It is easy to use just set EnableViewState property either to True or Falseo We can specify encryption mode, page size in version 2.0o Page size by default is -1(unlimited) we can specify bytes.o Disadvantage

Large volume of data ke case me performance is slowo Scope

Current page only.

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 stateo In this we can only store text not objecto Scope

Only on current page

Control State

o In this custom control (made by programmer) ki state management hoti hai

It’s me - 144 -

Page 145: Chottu Sharma Notes

Server Side State Management

Application

o When first user site kholta hai Application Start event fire hota haio 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 objectso Scope -- Thought-out the applicationo Application variable sabhi user ke liye same hota hai.o Hit counter( to view visitors) is example of this state management

Session

o Server generates 2 copies of unique sessionId.o One copy on client side(in session cookie) other on server side(memory)o In .Net we can create cookie less application then there is QueryString in

URL.o SessionId’s length is 128 bits.o Session expiry time by default is 20 min. we can change it.o Session.Avendon forcefully expires the session, including when browser is

closed.o If we open a new window then we get the same sessionIdo Types of Session State

In process (By Default) To store session in same process where application is

running Drawbacks

o If we reset the webserver session automatically destroys that’s y we cant used this in secure sites

Out process To store session on different process Advantage

o If we reset the server session destroy nahi hote. Modes

o State server To store session on different server Note: To implement this we must start

ASP.Net State Service. If we reset ASP.Net State Service Session

destroy ho jate hai.

It’s me - 145 -

Page 146: Chottu Sharma Notes

o SQL Server We store session in SQL database Two type of system define database

Temp Dbo If we reset SQL server

service then Temp Db ka data delete ho jata hai

Asp Stateo Ye data permanent hai.

o Out process ke case me session end event file nahi hota.

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

Place two textboxes and a button

protected void Button1_Click(object sender, EventArgs e){ if (TextBox1.Text == "abc" && TextBox2.Text == "xyz") { HttpCookie ck = new HttpCookie("myckk"); ck.Values.Add("uname", TextBox1.Text); // subkey ck.Values.Add("upass", TextBox2.Text); // subkey ck.Expires = DateTime.Now.AddMinutes(30); // if u don't specify the expiry time then cookie will destroy as soon as u close the browser // or u can specify this like //ck.Expires=DateTime.Now.Add(new TimeSpan(3,45,35)); // 3hr 45min 35sec Response.Cookies.Add(ck); Response.Redirect("default2.aspx"); }}

Add new page and place two textboxes, a label and a button

protected void Button1_Click(object sender, EventArgs e){ HttpCookie k = Request.Cookies["myckk"];

It’s me - 146 -

Page 147: Chottu Sharma Notes

if (k == null) { Label1.Text = "cookies not created"; } else { if (k.Values["uname"].ToString() == TextBox1.Text && k.Values["upass"].ToString() == TextBox2.Text) { Label1.Text = "welcome"; } else { 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);

It’s me - 147 -

Page 148: Chottu Sharma Notes

////////////////////////////////////////////////////////////// To Read Value//

///////////////////////////////////////////////////////////

Response.Write(Request.Cookies["un"].Value);

///////////////////////////////////////////////////////////

HttpCookie d = Request.Cookies["un"]; Response.Write(d.Value);

//////////////////////////////////////////////////////////// To read Sub Key

//////////////////////////////////////////////////////////

Response.Write(Request.Cookies["ui"]["un"].ToString()); Response.Write(Request.Cookies["ui"]["up"].ToString());

/////////////////////////////////////////////////////////

HttpCookie qq = Request.Cookies("ui"); Response.Write(qq.Value["un"].ToString); Response.Write(qq.Value["up"].ToString);

///////////////////////////////////////////////////////// To print all the Cookies and thire value

///////////////////////////////////////////////////////

Int32 i; for (i = 0; i < Request.Cookies.Count; i++) { HttpCookie a = Request.Cookies[i]; if (a.HasKeys) { System.Collections.Specialized. NameValueCollection nv; nv = a.Values; // Array ban jayega values ka String[] ar = a.Values.AllKeys; // Sub keys ke name ka array Int32 j; for (j = 0; j < nv.Count; j++) ; { Response.Write("Sub Key Name:"+ar[j]. ToString()+"Value:"+nv[j]. ToString() + "<br>"); }

It’s me - 148 -

Page 149: Chottu Sharma Notes

}

///////////////////////////////////////////////////////////// To restrict for path

//////////////////////////////////////////////////////////

kk.Path = "admin"; // this cookie work with admn folder only

QueryString

Place 2 textboxes and one button

protected void Button1_Click(object sender, EventArgs e){ Response.Redirect("default2.aspx?ab="+TextBox1.Text + "&ab1="+TextBox2.Text); // use "?" phele variable ke sath aur "&" rest ke sath}

Default2.aspx

Place a label and one button

protected void Page_Load(object sender, EventArgs e){ Label1.Text = "Welcome:" + Request.QueryString["ab"].ToString() + Request.QueryString["ab1"].ToString();

}

It’s me - 149 -

Page 150: Chottu Sharma Notes

To Open Calender in popup window

Place a textbox and a button

<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

Place a calender control Calender DayRender event

It’s me - 150 -

Page 151: Chottu Sharma Notes

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. opener.document.{0}.value='{1}';window.close()", Request.QueryString["ab"].ToString(), e.Day.Date.ToShortDateString()); e.Cell.Controls.Add(lk);}

To check whether cookies are enable or disable at client side

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;

It’s me - 151 -

Page 152: Chottu Sharma Notes

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); } Response.Redirect(d + "?aa=" + d1); }

ViewState

Place a label, button and a grid view

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

It’s me - 152 -

Page 153: Chottu Sharma Notes

SqlDataAdapter adp = new SqlDataAdapter("select * from tbemp", "database=dbemp;uid=sa"); DataSet ds = new DataSet(); adp.Fill(ds); return ds; }}

Panel on same screen

Place 4 panel and place buttons on them Next and prev

protected void Page_Load(object sender, EventArgs e){ if (Page.IsPostBack == false) { ViewState["ctr"] = 1; Panel1.Visible = true; Panel2.Visible = false; Panel3.Visible = false; Panel4.Visible = false; }}public void Btn_Next(object sender, EventArgs e){ String st; st = "Panel" + ViewState["ctr"].ToString(); Panel p = (Panel)(Page.FindControl(st)); p.Visible = false; ViewState["ctr"] = Convert.ToInt32(ViewState["ctr"]) + 1; st = "Panel" + ViewState["ctr"].ToString(); p = (Panel)(Page.FindControl(st)); p.Visible = true;}

It’s me - 153 -

Page 154: Chottu Sharma Notes

public void Btn_Prev(object sender, EventArgs e){ String st; st = "Panel" + ViewState["ctr"].ToString(); Panel p = (Panel)(Page.FindControl(st)); p.Visible = false; ViewState["ctr"] = Convert.ToInt32(ViewState["ctr"]) - 1; st = "Panel" + ViewState["ctr"].ToString(); p = (Panel)(Page.FindControl(st)); p.Visible = true;}

In source file add OnClick with Prev and Next button

Next Button OnClick="Btn_Next" Prev Button OnClick="Btn_Prev"

Application (Hit Counter)

Add New Item Global Application Class

void Application_Start(object sender, EventArgs e) { // Code that runs on application startup Application["ctr"] = 0;

}

void Session_Start(object sender, EventArgs e) { // Code that runs when a new session is started Application.Lock(); Application["ctr"] = Convert.ToInt32(Application["ctr"]) + 1; Application.UnLock(); }

Default.aspx.cs

protected void Page_Load(object ,EventArgs) { Label1.Text = Application["ctr"].ToString(); }

It’s me - 154 -

Page 155: Chottu Sharma Notes

To check the no. of user currently using this site

void Session_End(object sender, EventArgs e) {

// Code that runs when a session ends. // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web.config file. If session mode is set to StateServer // or SQLServer, the event is not raised. Application.Lock(); Application["ctr"] = Convert.ToInt32(Application["ctr"]) - 1; Application.UnLock(); }

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

Place a gridview & a button

protected void Page_Load(object , EventArgs e) { GridView1.DataSource = (DataSet)(Session["ss"]); GridView1.DataBind();

It’s me - 155 -

Page 156: Chottu Sharma Notes

} protected void Button1_Click(object, EventArgs e) { Session.Abandon(); // To expire session forcefully }

Session State

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

protected void Button1_Click(object , EventArgs e) { Session["ss"] = "hello"; Response.Redirect("default2.aspx"); }

Default2.aspx.cs

Place label

protected void Page_Load(object, EventArgs e) { if (Session["ss"] != null) { Label1.Text = Session["ss"].ToString(); } else { Label1.Text = "No Data"; }

}

To reset Web server

Goto visual studio command prompt Type --- iisreset (data in inproc will lost)

It’s me - 156 -

Page 157: Chottu Sharma Notes

Out Process

State Service

Add web config file

<system.web> <sessionState mode="StateServer" stateConnectionString="tcpip=127.0.0.1:42424" timeout="20"></sessionState>

State server uses Asp.net State Service To start it Control Panel Administrator Tool Services Asp.NetStateService Right Click start If we reset this service we will lost the session

SQL Server

In Web Config write

<system.web><sessionState mode="SQLServer"

sqlConnectionString="server=cs;uid=sa"></sessionState>

It uses two databases TempDb ASPStateDb

To tell database In .Net command mode For TempDbAspnet_regsql.exe –S sac –E –ssadd -sstype t

For ASPStateDbAspnet_regsql.exe –S sac –E –ssadd -sstype p

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

It’s me - 157 -

Page 158: Chottu Sharma Notes

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

Place DataList, SqlDataSource and configure it Datalist Properties repeatColumns 2 In source

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

Set DatKeyField bookId

protected void DataList1_SelectedIndexChanged(object, e){ Response.Redirect("Default2.aspx?bid=" + DataList1.DataKeys[DataList1.SelectedIndex]. ToString());}protected void DataList1_ItemCommand(object source, e){

It’s me - 158 -

Page 159: Chottu Sharma Notes

if (e.CommandName == "Cart") { Response.Redirect("default3.aspx?bid=" + DataList1.DataKeys[e.Item.ItemIndex]. ToString()); }}

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>

It’s me - 159 -

Page 160: Chottu Sharma Notes

</ItemTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /> </ItemTemplate> </asp:TemplateField></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

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting"

It’s me - 160 -

Page 161: Chottu Sharma Notes

OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating"> <Columns> <asp:BoundField DataField="ordId" HeaderText="Id" ReadOnly="True" /> <asp:BoundField DataField="ordTit" HeaderText="Title" ReadOnly="True" /> <asp:BoundField DataField="ordAuthor" HeaderText="Author" ReadOnly="True" /> <asp:BoundField DataField="ordPub" HeaderText="Publisher" ReadOnly="True" /> <asp:BoundField DataField="ordPrice" HeaderText="Price" ReadOnly="True" /> <asp:BoundField DataField="ordQty" HeaderText="Quantity" /> <asp:BoundField DataField="ordAmt" HeaderText="Amount" ReadOnly="True" /> <asp:CommandField ShowEditButton="True" /> <asp:CommandField ShowDeleteButton="True" /> </Columns></asp:GridView>

using System.Data.SqlClient;public partial class Default3 : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { if (Session["ss1"] == null) { DataTable tb = new DataTable("Table"); tb.Columns.Add(new DataColumn("ordId", Type.GetType("System.Int32"))); tb.Columns.Add(new DataColumn("ordTit", Type.GetType("System.String"))); tb.Columns.Add(new DataColumn("ordAuthor", Type.GetType("System.String"))); tb.Columns.Add(new DataColumn("ordPub", Type.GetType("System.String"))); tb.Columns.Add(new DataColumn("ordPrice", Type.GetType("System.Int32"))); tb.Columns.Add(new DataColumn("ordQty", Type.GetType("System.Int32"))); tb.Columns.Add(new DataColumn("ordAmt", Type.GetType("System.Int32"))); tb.Columns["ordAmt"].Expression= "ordQty*ordPrice";

It’s me - 161 -

Page 162: Chottu Sharma Notes

Session["ss1"] = tb; } if (Page.IsPostBack == false) { String st; 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); 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)

It’s me - 162 -

Page 163: Chottu Sharma Notes

{ GridView1.EditIndex = -1; GrdBind(); }}

SECURITYSecurity include

1. Authorization means permission to user.

2. Authentication

Authentication of IIS1. 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 Types1. 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

It’s me - 163 -

Page 164: Chottu Sharma Notes

Username  

Password Button

Webconfig file

<authentication mode="Forms"><forms name="cookie" loginUrl="login.aspx"></forms>

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

It’s me - 164 -

Page 165: Chottu Sharma Notes

Default.aspx

Label

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

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

It’s me - 165 -

Page 166: Chottu Sharma Notes

protected void Button2_Click(object sender, EventArgs e) { if (FormsAuthentication.Authenticate(TextBox1.Text, TextBox2.Text)) { FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, 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

It’s me - 166 -

Page 167: Chottu Sharma Notes

PropertyNavigationURLDefault2.aspx

PropertyNavigationURLDefault3.aspx

ROLE BASED SECURITY

Create table tbusr

Uname varchar(50)

Upass varchar(50)

Urole varchar(50)

Add some record eg

Uname Upass Urole

Faisal khan admin

Sachin gupta user

Charu satia admin|user

Add 2 folder in solution explorer

Adm--> default2.aspx,default3.aspx

Usr-->default4.aspx,default5.aspx

Roles assign to folder in webconfigfile

Add webconfig file

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

It’s me - 167 -

Page 168: Chottu Sharma Notes

<location path ="usr"> <system.web > <authorization > <allow roles ="user"/> <deny users ="*"/> </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,

It’s me - 168 -

Page 169: Chottu Sharma Notes

dr[2].ToString(), FormsAuthentication.FormsCookiePath);

//Here we encrypt the ticket n stored st(ticket) and cookie name fromwebconfig file into cookie or with the help of querystring passed this value into default.aspx

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

FormsAuthenticationTicket tkt Ticket is used for passing customise data

whatever we want.

1st Parameter is ticket version no. assign with multiple tickets.

2nd Parameter username.

3rd Parameter issued ticket datetime

4th Parameter expire time

5th Parameter cookies temp(false) or permanent(untill web browser session

expire).

6th Parameter string userdata dr[2] contain table coloumn Urole.

7th Parameter string cookies path.

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.

It’s me - 169 -

Page 170: Chottu Sharma Notes

HttpContextEnclupulate all http specific information about an individual http request.

<%@ Application Language="C#" %><%@ Import Namespace ="System.Security.Principal"%><script runat="server">

void Application_Start(object sender, EventArgs e) { // Code that runs on application startup } void Application_End(object sender, EventArgs e) { // Code that runs on application shutdown } void Application_Error(object sender, EventArgs e) { // Code that runs when an unhandled error occurs } void Session_Start(object sender, EventArgs e) { // Code that runs when a new session is started } void Session_End(object sender, EventArgs e) { // Code that runs when a session ends. // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web.config file. If session mode is set to StateServer // or SQLServer, the event is not raised. }

protected void Application_AuthenticateRequest(object sender,EventArgs e) { if (HttpContext.Current.User!= null) { FormsIdentity fi;

//We get current user identity(ticket) fi = (FormsIdentity)(User.Identity); FormsAuthenticationTicket tk; tk = fi.Ticket; //Get user role with ticket, split the role and stored into array. string ud = tk.UserData; string[] ar = ud.Split('|');

//fi contain identity of user and array ar contain role which is known as generic principal.

HttpContext.Current.User = new GenericPrincipal(fi, ar);

It’s me - 170 -

Page 171: Chottu Sharma Notes

} }</script>

Default.aspx

2 Hyperlink Button

PropertyNavigationURLadm/Default2.aspx,Default3.aspx

PropertyNavigationURLusr/Default4.aspx,Default5.aspx

It’s me - 171 -