It’s me


ASP 2.0 using c# or Database  SQL Server, Xml • It is used for web development

.Net Architecture ASP.Net web Application  BCL CLR OS BCL  Base class language CLR  Common Language Runtime OS  Operating System CLR It is an environment which manages the execution of coding. It manages:• • • Memory management Garbage collection To support multiple language  Windows Application

(Note: difference b/w CLR n JVM is that JVM only support single language i.e. java) BCL Collection of standard class or common class which we can use .net supported language E.g. - in VB.Net we use “integer” n in c# we use “int” but we can use “int16”, “int32” in both. • • Note: 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-

• • •

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 • • C# • • 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 C# J# C1 C2 C3 MSIL JIT Native code

It’s me


adm tools --.• • MSIL  Microsoft Intermediate Language (m/c independent) 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.0 • In place compilation (by default)  Single file compiler at run time in which changes has been done.IIS --.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 components To change home directory Control panel --.CS ---web sites--.  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”.1 version It is not loaded on XP-home edition We can load it through Control panel --.default web site (Right click)--.Properties --.add remove files--.Net 2.Net • Server IIS (Internet information service) it is used with 1.home directory (By default “c:\netpub\wwwroot”) To check weather server is running or not It’s me -4- .  It makes compilization file for each file starting with “app_web” and after that Any random generated name like abc ----.

adm tools --.CS ---web sites--.IIS --.cs  code file (C#) Concept of Partial class is introduced in ver 2. Benefit of this system code(used by system) can be store in one partial class n developer code in another.0 which means we can divide the class into number of parts.aspx  designing or presentation .Net web site Location (specify server) file system (web server) HTTP (IIS) Language  Visual basic C# Extension • • • • . property. We can inherit only one class not multiple inheritance in .aspx.Control panel --.0 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.aspx. If start n stop is working IIS is running Web Server included in version 2.default web site (Right click)---start/stop. namespace.vd  code file (VB) .net We differciate method. class by there symbol {} namespace 3 boxes class Pink box method etc Bijali event Hand property Namespace is collection of classes it may be nested All procedures which have handles in the end are events. • • • • It’s me -5- .

 It is read-only.isPostBack is false only first time when page is loaded. • To stop scrolling of window when page is posted back It’s me -6- . page will be light Weighted due to less labels Ctrl + space for intelligence help. write End sub In c# Void page_load () { Label1.toString().now End if  page. It has to parameters 1st for reference and 2nd for manage event data Windows required  Solution explorer  Toolbox HTML Control (background compatibility) Run on client side and are browser dependent Web Server control Run on server side and are browser independent  Property window(f4) Two types of layout  Grid layout (available in ver 1.isPostBack = false then = datetime.text = datetime. we validation n checks can be used but with variables these r not possible.• • Page load event is fired first without even calling this event. • • • Program 1: • Display current date & time in label Sub Page_load Label1.text = datetime. Difference b/w property n variable is that property can be read only.1)  Flow layout (available in both version) Advantages  we work as notepad. } • To run a code only first time the page is loaded we use If page.

click If sender is button 3 then Sum Else if sender is button4 then Mul Else Divide In C# We change in HTML.text) +convert.Toint32(textbox1.text).text=convert. button5. In C# Textbox3. To use common handle i. • • In Vb.Me. To add two numbers Textbox3.text) + convert. use onClick method for this purpose It’s me -7- .text)).click.Toint32 ( = true • • To compile line by line click in front of line where u want to place break and then press f10.Toint32(textbox2.e.text = convert.button4. one procedure handling more then one event we add handles in the end of procedure in type casting is automatic but in C# we have to do it manually.Toint32( like Handles button3.Tostring(convert.

• Various legacy VB functions (provided in the Microsoft. This allows pointer arithmetic etc. Many of these can be harmful to performance if used unwisely. But both have access to the same framework libraries. Arguably this makes the class harder to understand. and there are tools which will do it with existing VB. but it's certainly a difference. where a method can declare that it handles an event. Language support for unsigned types (you can use them from VB. case-insensitive approach. but they aren't in the language itself). where an interface which is already implemented in a base class can be re-implemented separately in a derived class. • Simpler (in expression .VisualBasic namespace.VisualBasic. but legacy libraries which don't have strongly typed interfaces become easier to use. others like C#'s terse syntax. 2. coming to VB. • Support for named indexers. Advantages of both languages Keyword Differences Data types Differences Operators Differences Programming Difference Advantages of both languages VB. 3. • • • • • XML documentation generated from source code comments. It’s me -8- . and can be used by other languages with a reference to the Microsoft. Again. rather than the handler having to be set up in code.NET code already.NET. it is not to be used lightly. as a lot of the normal safety of C# is lost (as the name • The VB. We will discuss about the differences in the following topics: 1. however. (This is coming in VB. and can improve performance in some situations. • The with construct: it's a matter of debate as to whether this is an advantage or not.) Operator overloading .NET parts of Visual Studio . Unsafe code. support for these is coming to VB.perhaps more complicated in understanding) event handling.NET C# • Support for optional parameters .NET with Whidbey (the code name for the next version of Visual Studio and .NET in Whidbey. • Support for late binding with Option Strict off .NET in Whidbey. 4. Explicit interface implementation.again.NET's natural language. However.dll).very handy for some COM interoperability. in the same way that member hiding normally does.NET compiles your code in the background. and many people believe they should be avoided for the most part.type safety at compile time goes out of the window.NET). 5.Some people like VB.

Keyword Differences Purpose Declare a variable VB.e. Shared. CreateObject() Sub void Function/method does not return a value Overload a function Overloads (No language keyword required for or method (Visual this purpose) Basic: overload a procedure or method) this Refer to the current Me object MyClass Make a nonvirtual n/a call to a virtual method of the current object GetChar Function [] Retrieve character from a string Declare a compound Structure <members> End struct. implies). people creating very large projects have found that the IDE slows down considerably as the project gets larger.While this is considered as an advantage for small projects. JITted. class. Note that unsafe code is still managed code.. or system default type (constructors) constructors Terminate an object n/a n/a directly Method called by the Finalize destructor system just before garbage collection reclaims an object7 // initialize to a value: Initialize a variable Dim x As Long = 5 It’s me -9- . and run within the CLR.NET Private. Friend. interface Structure data type (Visual Basic: Structure) Initialize an object Sub New() Constructors. Public. Static1. i. Protected. it is compiled to IL. Dim C# (keywords include userdefined types and built-in types) declarators Const const Declare a named constant new Create a new object New.

where it is declared Take the address of a function members.Gas // or use default ) // constructor: int x = new int(). delegate AddressOf (For class volatile n/a. (All variables must be declared prior to use) obj == null null n/a n/a by using indexers base interface class C1 : I1 class abstract sealed enum const (Applied to a field declaration) . Specify that a class NotInheritable cannot be inherited Enum <members> End Enum Declare an enumerated type Const Declare a class constant It’s me Dim c As New _ int x = 123.10 - . An instance of the class cannot be created. Car(FuelTypeEnum. this operator returns a reference to a function in the form of a delegate instance) Declare that an object n/a can be modified asynchronously Option Explicit Force explicit declaration of variables obj = Nothing Test for an object variable that does not refer to an object Value of an object Nothing variable that does not refer to an object Test for a database IsDbNull null expression Test whether a n/a Variant variable has been initialized Default Define a default property Refer to a base class MyBase Declare an interface Interface Specify an interface Implements (statement) to be implemented Class <implementation> Declare a class Specify that a class MustInherit can only be inherited.

else Then. End Select switch. C++) Shadowing Hide a base class member in a derived class Declare a typesafe Delegate reference to a class method WithEvents Specify that a variable can contain an object whose events you wish to handle Specify the events for Handles (Event procedures which an event can still be associated with a procedure will be WithEvents variable by called naming pattern. Else. if. End If While. goto.. finally. ElseIf . break If .. continue It’s me . Case.Derive a class from a Inherits C2 base class Override a method Overrides Declare a method that MustOverride must be implemented in a deriving class Declare a method that NotOverridable (Methods can't be overridden are not overridable by default. Case Else.... Do [While.. specific keyword) n/a n/a try... then) Loop structure Select Case .member> expression once..member> order to access End With multiple members Structured exception Try <attempt> Catch handling <handle errors> Finally <always execute> End Try class C1 : C2 override abstract sealed virtual n/a delegate (Write code . Until] do. throw Decision structure (selection) Decision structure (if . while. property (Visual Basic). case. default. or property accessor (C#. catch. in <.11 - .) Overridable Declare a virtual method.) Evaluate an object With objExpr <.

JScript) Visible only within Private the project (for nested classes.12 - . Redim Reallocate array Visible outside the Public project or assembly Invisible outside the Friend assembly (C#/Visual Basic) or within the package (Visual J#.. Next For Each . foreach int[] x = new int[5].] Next Dim a() As Long Dim a() As Long = {3. within the enclosing class) Accessible outside Public class and project or module Accessible outside Friend the class.. 4.. RaiseEvent SyncLock Yes use Platform Invoke event lock It’s me . 2.. 4.. int[] x = new int[5] { 1.. but within the project Private Only accessible within class or module Protected Only accessible to current and derived classes Preserve procedure's Static local variables Shared Shared by all instances of a class ' Comment code Rem n/a public internal private public internal private protected n/a static //. 5}. Until] For .. 5} for.. [Exit For.. Loop [While.(conditional) Loop structure (iteration) Declare an array Initialize an array . 3. [Exit For]. /* */ for multi-line /// for XML comments comments Case-sensitive? Call Windows API Declare and raise an event Threading primitives No Declare <API> Event.

char (Unicode character) int long float double Operators Differences Purpose Integer division Modulus (division returning only the remainder) Exponentiation Integer division Assignment Concatenate Modulus Bitwise-AND Bitwise-exclusive-OR VB.NET \ Mod C# / % ^ \= &= NEW n/a /= += %= &= ^= n/a n/a n/a It’s me .13 - .Go to Goto goto Data types Differences Purpose/Size Decimal Date (varies) 1 byte 2 bytes 2 bytes 4 bytes 8 bytes 4 bytes 8 bytes VB. Char (Unicode character) Integer Long Single Double C# decimal DateTime string byte bool short.NET Decimal Date String Byte Boolean Short.

CType (type) ++ -- n/a n/a n/a AddressOf Not Not (unsafe mode only) & (unsafe mode only. () Cint. CDbl. n/a n/a n/a And Xor Or And Or If Function () n/a (Unsafe mode only) Programming Difference Purpose Declaring Variables Comments VB.Bitwise-inclusive-OR Equal Not equal Compare two object reference variables Compare object reference type Concatenate strings Shortcircuited Boolean AND Shortcircuited Boolean OR Scope resolution Array element Type cast Postfix increment Postfix decrement Indirection Address of Logical-NOT One's complement Prefix increment Prefix decrement Size of type Bitwise-AND Bitwise-exclusive-OR Bitwise-inclusive-OR Logical-AND Logical-OR Conditional Pointer to member n/a = <> Is TypeOf x Is Class1 & AndAlso OrElse .NET Dim x As Integer Public x As Integer = 10 ' comment x = 1 ' comment C# int x. // comment /* multiline It’s me .. also see fixed) * ! ~ ++ -sizeof & ^ | && || ?: . and base [ ] ... |= == != == x is Class1 + && || .14 - . int x = 10.

WriteLine("Zero ").WriteLine( "The number is {0}". break.WriteLine("One" ). case 2: Console.WriteLine( _ public int Z = 100. } Public Shadows Z As String = "*" public class DervCls : public Shadows Sub Test() BaseCls MsgBox("The number is " & n) Next It’s me . i++) Console. nCnt++. For Each prop In obj foreach(prop current in obj) prop = 42 { Next prop current=42.Console. } else { nTotal +=nCnt.15 - . nCnt += 1 Else nTotal += nCnt nCnt -= 1 End If Select Case n Case 0 MsgBox ("Zero") ' Visual Basic .Console. } switch(n) { case 0: Console. case 1: Console. i <= 10. Case 1 MsgBox ("One") Case 2 MsgBox ("Two") Case Else MsgBox ("Default") End Select Selection Statements FOR Loops For n = 1 To 10 Hiding Base Class Members for (int i = 1. break. nTotal += nCnt ' Same as nCnt = nCnt + 1.WriteLine("Two" ).NET exits ' the Select at ' the end of a Case. break. "Test in BaseCls") public void Test() End Sub { End Class System.WriteLine("?").Rem comment Assignment nVal = 7 comment */ nVal = 7.WriteLin e( Public Class DervCls "Test in BaseCls"). Inherits BaseCls } ' The shadowing element. } Public Class BaseCls public class BaseCls ' The element to be shadowed { Public Z As Integer = 100 // The element to be public Sub Test() hidden System. if (nCnt <= nMax) { nTotal += nCnt. default: Console. } Statements Conditional If nCnt <= nMax Then ' Same as nTotal = Statements ' nTotal + nCnt. i). nCnt--. break.

n++. } } ' Test at start of loop while (n < 100) While n < 100 .16 - . DObj...Console.WHILE Loops Parameter Passing by Value System.Console. System.Z).Console. n += 1 End While ' ' The argument Y is /* Note that there is 'passed by value. "class: " & DObj.Console. "Accessed through base "&_ // Access through derived "class: " & BObj.Console. the to either pass the reference ' changes do not affect x. } ' by enclosing // Calling the method: ' the parameters in ABC(i). { ' regardless of how .WriteLine( ' DervCls widens to BaseCls. ' they are declared.Console.Test() System.WriteLine( _ { "Test in DervCls") // The hiding element End Sub public new string Z = "*".WriteLine( _ DervCls().Z) //class System. ' Same as n = n + 1.Test(). // The method: ' You can force parameters to void ABC(int x) ' be passed by value. public class UseClasses Dim DObj As DervCls = { New DervCls() // DervCls widens to BaseCls Public Sub ShowZ() BaseCls BObj = new System. End Class public new void Test() { Public Class UseClasses System.WriteLine(_ DervCls DObj = new "Accessed through derived "&_ DervCls().WriteLine( "Accessed through" + " derived class:{0}". You can choose 'If ABC changes y.Test() { DObj.Z). Dim BObj As BaseCls = } New DervCls() } ' Access through derived ' class. (essentially a pointer).WriteLine( End Sub "Accessed through " + End Class "base class: {0}". DObj. ' extra parentheses. "Test in DervCls"). BObj. no way to pass reference Public Sub ABC( _ types (objects) strictly ByVal y As Long) by value.*/ ABC(x) ' Call the procedure.Test(). or End Sub a reference to the reference (a pointer to a pointer). BObj.Z) public void ShowZ() BObj. ABC((x)) It’s me .

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.

Structured Try If x = 0 Then Exception Throw New Exception( _ Handling "x equals zero")

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

/* 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); // try-catch-finally try { 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"); }

o = Nothing o = null; Set an Object Reference to Nothing Initializing Dim dt as New System.DateTime( _ System.DateTime dt = 2001, 4, 12, 22, 16, 49, 844) new System.DateTime( Value 2001, 4, 12, 22, 16,

It’s me

- 17 -


49, 844);

New Features of both languages in 2005 version
VB.NET C# Visual Basic 2005 has many new and improved With the release of Visual Studio 2005, language features -- such as inheritance, the C# language has been updated to interfaces, overriding, shared members, and version 2.0. This language has following overloading -- that make it a powerful object- new features: oriented programming language. As a Visual Basic developer, you can now create 1. Generics types are added to the multithreaded, scalable applications using language to enable programmers to explicit multithreading. This language has achieve a high level of code reuse following new features, and enhanced performance for collection classes. Generic types 1. Continue Statement, which can differ only by arity. Parameters can also be forced to be specific immediately skips to the next iteration types. of a Do, For, or While loop. 2. Iterators make it easier to dictate 2. IsNot operator, which you can avoid how a for each loop will iterate using the Not and Is operators in an over a collection's contents. awkward order. 3. // Iterator Example 3. Using...End. Using statement block 4. public class NumChar ensures disposal of a system resource 5. { when your code leaves the block for 6. string[] saNum = { 7. "One", "Two", "Three", 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 = nf 10. c.Text = "This is" &_ 11. "12-point Arial bold" 12. End Using 8. "Four", "Five", "Six", 9. "Seven", "Eight", "Nine", 10. "Zero"}; 11. public 12. System.Collections.IEnume rator 13. GetEnumerator() 14. { 15. foreach (string num in

It’s me

- 18 -

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.

saNum) yield return num; } } // Create an instance of // the collection class NumChar oNumChar = new NumChar(); 22. // Iterate through it with foreach 23. foreach (string num in oNumChar) 24. Console.WriteLine(num); 25. Partial type definitions allow a 16. 17. 18. 19. 20. 21.

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. 32. 8. There are eight new compiler options: a. /langversion option: Can

It’s me

- 19 -

f. It’s me . h. The /doc option generates an XML documentation file based on comments within your code. The /platform option specifies the processor to be targeted by the output file. The /nostdlib option prevents the import of mscorlib.b. e. The /noconfig option causes the compiler to ignore the Vbc. f. c. The /errorreport option provides a convenient way to report a Visual Basic internal compiler error to Microsoft. #pragma warning: Used to disable and enable individual warnings in code.20 - . which defines the entire System namespace. The /filealign option specifies the size of sections in your output file. /linkresource option: Contains additional options. be used to specify compatibility with a specific version of the language. /keycontainer and /keyfile: Support specifying cryptographic keys.dll. g.rsp file. in those situations where it is necessary to explicitly specify it. c. d. b. The /unify option suppresses warnings resulting from a mismatch between the versions of directly and indirectly referenced assemblies. /errorreport option: Can be used to report internal compiler errors to Microsoft over the Internet. /platform option: Enables you to target IPF (IA64 or Itanium) and AMD64 architectures. d. e.

Types of validators There are 6 types of validators • Required field validator ( for empty check). • Compare if not jscript at client then they run on server.Validation.0 E.1 but can do this in 2. Required field validation properties • • controlToValidate  name of textbox to check Text  message Compare validation properties It’s me . In asp JavaScript will not run if client site don’t have JavaScript In . We can compare  controls (like password n confirm password)  value (age must be greater then 18)  data type check (salary must be no.g.Net 1. • We not able to associate controls with validators in ASP.VALIDATION AND CHECKS • • • • Validations are provided by Microsoft in Vb. “username n pass” and search is check by different button.) • Range validator • Regular expression validator • Pre define format (valid email address) • Custom validator • Validation summary • Web.21 - .net Run on client site.UI.js is the file name in which jscript of all these validator are available.

22 - . 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. less.• • • 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.0  set the causes validation property to false to disable the validation of button • • • It’s me . Text * errorMessage  Empno empty To run validation summary we need a button To make popup window go to validation summary property ShowMessageBox  true Show Summary  false Addition properties in version 2.

} } 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.checked == true) { Textbox1.redirect(“default.• • •  validation group property of validator (textbox. • • • Basic Controls in . To go to new page we have 3 methods o Response.font. } Else { Textbox1.bold = true.redirect() o Server.bold = false. validationSummary n of button) o ValidationGroup  a  property of validator o SetfocusonError  to go directly to the error point skip correct places.aspx When we want to move to next page without submitting the current page we use hyperlink. • Radio button It’s me .font. 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).net • checkbox checkbox1_checked changed event { If(checkbox.aspx”) To go to next page by hyperlink properties o Text  next o Navigate URL  default.23 - .execute() To go to next page by button o Response.transfer() o Server.

• Checkbox list o DataBound control  it is collection of checkboxes o Useful when we want to make checkboxes at runtime. o Properties • Repeat columns  value • Repeat direction  vertical/ horizontal o 3 method of defining the checkboxes • Edit items • Selected  by default selected • Enabled  disable to user to change it • Run time data entry Page_load { If(page. } /* For collection • We must have namespace Using System. It’s me .add(“abc”).itms.o Property GroupName to mention the group.forecolor = color. */ Arraylist arr = new ArrayList(). o They have only selected whenever we click on them not lick checkbox. radiobutton_checked changed event { Textbox1.24 - .add(“xyz”).itms. } o We must include a namespace to use color Using System. • Collection is data structure to store items • Arraylist  array of objects which increase its size dynamically.  by default has size equal to 6 characters.collection.isPostBack == false) { Checkboxlist1.

”1”)).item[i].dataSource = arr.25 - .text+=checkboxlist1.dataBind().add(new listItem(“aa”. } } • Textbox property Textmode  multiple line (to display data in multiple line) • To store different value in checkbox at behind (hidden name  value.add(“abc”). checkboxlist1.selected==true) Textbox1.i<checkboxlist1.value.item[i].add(“xyz).items[0].items[i].arr. arr.count. i++) { If(checkboxlist1. It’s me . } Button1_click { For(int32 i=0. checkboxlist1. text +”\n”. display name text)  To add value field Checkboxlist1.items.items.enabled = false.  To retrieve value Checkboxlist1. // both these methods work together Checkboxlist1.

Less space in access. next time the procedure will be faster than before.Net (ActiveX Data Object) • • It is an environment which is design by Microsoft for database handling.DATABASE HANDLING Difference between MsAccess and SQL • • • • • • • In oracle & SQL there are triggers. Two main components o XML ( it is lincense free. Database server and application server are two different things. 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). • Database connectivity • There are 4 ways of connectivity with database o ODBC (Open DataBase Connectivity) It’s me Used to connect to each n . Less security in access. In Web development 99% we use SQL. cursor generally know as compile objects which are store in database and executed in database only due to which traffic will not slow down. platform independent and the fastest way of data transfer ). functions. It design while having web application in mind.9% used by the those companies which have own server.26 - . Store procedure once executed. Oracle is 99. procedure. ADO.

security o ORACLEClient (specifically used with Oracle server. It is included in . o It is for project configuration e.ldf ( log database file) To create database o View  server explorer o In last there is “server” to know the server name o Data connection(right click)  create new SQL server DB o Mention these fields • Server name  sac • Use SQL server authentication • Username  “sa” (default) • New database name  dbemployee o Now this dbemployee will be added in data connection o Sac. It is included in .net) Better performance and Compatibility • Two main files are there o . o Non compile file where as module has to compile o XML based.0 (we cant view the file without coding) o Intelligence help is provided in version 2. Web.config is single in one project. session setting etc o To add web.mdf (Microsoft database file) o .dbemployee  table(right click)  add new table o 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.0 o It can be multiple in single project but machine.o OLEDB (Object Linking & Embedding) every server o SQLClient (specifically used with Ms SQL server. Case sensitive o Secure in version 2.g. uid changes instead of going to each n every page we just change it in web.27 - • • • .config.config file o It is used to store connection string. It is to manipulate it if server name.config • Website  add new item  web conf file o Add connection string in this file <connection string> It’s me .

o In 1.Net we use “me” Con.<add name=”nonu” connectionString=”server=sac.uid=sa”> And Excess this as configurationSetting. database=dbemployee. connectionString.smartNavigation = true. // in c# we use “this” and in VB.0 we add connection string in <appsettings> tag = ConfigurationManager. key uid=sa. If (con. pwd=admin”/> It is used if u have mentioned password </connection string> o Server name in connection string is not compulsory if ur server is same system where application is running. // before using open() we must check the state of connection otherwise It’s me .State ==ConnectionState. // ConfigurationManager is used to read connection string.ConnectionString[“nonu”].data. // SQLConnection class is used to establish connection Page_load { This.Closed) { Con.AppSettings[“cs”] • Difference between o Hash  stores key as well as value o Array  stores only value We should add • Using System. <add key=”cs” value=”database=dbemp. } // open() make connection active & make connectivity with SQL server.SQLClient. Class_default { SQLConnection con = new SQLConnection().28 - .

executeNonQuery(). // commandText is used to specify query or store procedure.isPostBack == false) textbox1.add(“@en”.parameters.CommandText. textbox2.toString(). textbox3.29 - .text = “ “.text.text = “ “. // connection established cmd.command=con.sqldbtype.parameters.text = “ “.Varchar. textbox4. value = textbox2.add(“@eno”.problem of connection pooling occur. } Button1_click // save { SQLcommand cmd = new sqlcommand().Int). update. cmd. Used for save.dispose().text).ToInt32(textbox1.text= getAuto(). // Sqldbtype is enumerator(user define datatype) cmd.value = convert. //textbox1. @eno are parameters with are used at runtime cmd. If(page. cmd. display cmd. } } } It’s me . // destructor textbox1. 50).toString(). // ExecuteNonQuery Execute the query and return the no. // SQLCommand bridge between data and database.text=getAuto().@ed@es)”. of data received. // 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.@en.text = “ “. delete.=”Insert into themp values(@eno.sqldbtype.

} Delete Code Button3_click //delete { SQLcommand cmd = new sqlcommand().executeNonQuery().parameters. value =textbox2. textbox3.Int). sqldbtype.text textbox3.command=con.add(“@en”.ToInt32 (textbox1.text } Display code Button4_click { = = = = “ “ “ “ “. textbox2.ToInt32(textbox1. cmd. It’s me .text. cmd. cmd.parameters. cmd. cmd.Update code Button2_click //update { SQLcommand cmd = new sqlcommand (). edd = @ed.Int).commandText=”delete from tbemp where empno=@eno”.text).text. cmd. textbox1.parameters.add (“@eno”. textbox4.sqldbtype .executeNonQuery ().text = “ “. “.command=con. “. cmd.30 - . “. textbox1.commandText=”update tbemp set ename=@en.parameters.add(“@eno”. cmd. 50). cmd. value = textbox2.value = convert. cmd. esal = @es where empno = @eno”.value = convert.Varchar. sqldbtype. 50).dispose ().dispose().text = “ “. cmd.sqldbtype.text = “ “.text = “ “. Varchar.text textbox4. cmd.add (“@en”.text).text textbox2.

cmd.parameters. // ExecuteReader just execute the query n store the data in variable(just for display) Listbox1. Listbox1.SQLcommand cmd = new sqlcommand(). We should close it after using it coz otherwise we can’t use it again like static method it has only one memory.commandText =”select * from tbemp”.selectedValue).command=con.31 - . It is segantal class used to pass reference just like abstract class. Listbox1_selectedIndexChanged { SQLcommand cmd = new sqlcommand (). SQLDataReader is used to view data.DataSource = dr.add (“@eno”.dispose(). Dr.dataTextField =”ename”.dataValueField =”empno”. Forward only ( only go in forward direction) It is the fastest way of data retrieval.DataBind().value = convert. // value at the back side of listbox (not visible) Listbox1.Int).connection = con. cmd. cmd. Sequential read.ExecuteReader (). } • Set the autoPostBack property of listbox1 equal to true.close(). cmd. It is read only. cmd. cmd. No need of “new” operator. // DataTextField display the data in listbox Listbox1.commandText=”select * from dbemp where empno = @eno”. sqldbtype. SQLDataReader dr.ToInt32 (listbox1. It’s me . /* • • • • • • • • */ Dr = cmd.

cmd.parameters.add (“@eno”, sqldbtype.Int).value = convert.ToInt32 (listbox1.selectedItem.text); // selectedValue to get the value behind the data selected // selectedItem.text to get the value display in the listbox SqlDataReader dr; Dr = cmd.ExecuteReader(); If(dr.HasRows) { Dr.Read(); // to read the next line Textbox1.Text = dr [“empno”].ToString(); Textbox1.Text = dr [“ename”].ToString(); Textbox1.Text = dr [“eaddress”].ToString(); Textbox1.Text = dr [“esal”].ToString(); } // convert the data to string coz by default they are objects Dr.close(); cmd.dispose(); } • 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 -

• • 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 value o 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 executed o Procedure is compiled in memory o 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.

• • •

• •

It’s me

- 33 -

Save procedure CREATE PROCEDURE insemp ( @eno int, @en varchar(50), @ed varchar(50), @es int ) AS Insert into tbemp values(@eno,@en,@ed,@es) • • When we save this CREATE will automatically changes to ALTER that means in future we can only alter this procedure. If we 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 dispemp AS It’s me - 34 -

Authentication procedure • Create table (tbuser) o Uname  varchar(50) o Upass  varchar(50) CREATE PROCEDURE loginCheck ( @u varchar(50).Select * from tbemp.commandText=”Procedure name”. CommandType tells us the type of command. @p varchar(50) ) AS Declare @ap varchar(50) SELECT @ap = upass from tbuser where uname = @u If @ap is null Return -1 Else If @ap = @p Return 1 Else Return -2 • • • • • If we don’t write anything in front of parameter then by default they are of type input. o Cmd. If uname is not valid then select statement return null in @ap.StoreProcedure.35 - .commandType=commandType. Now instead of writing command in front end we write these two lines o Cmd. It’s me . To enter data directly to table  right click on the table in the server explorer  show table data. Find procedure CREATE PROCEDURE findemp ( @eno int ) AS Select * from tbemp where empno = @eno • We can store more than one query in one procedure when we do more than one work in a single step like when we click on button then Save n Update will run simultaneous.

commandType = commandType.• • Add two three accounts in the table Design the front view design of login screen Using System.parameter[“@ret”].commandText = “loginCheck”.varchar.36 - . // value will be added in @ret Int32 k =convert.SQLVbType.closed) { Con.StoreProcedure cmd. cmd. cmd.parameter. SQLDbtype. String p) { SQLCommand cmd = new SQLCommand().add(“@p”.Direction = ParameterDirection. P1.value=p.pamameter.connectionSting. 50). cmd. cmd.returnValue.state = = connectionState.ExecuteNonQuery().Toint32(cmd.add(“@u”. 50).SQLClient.value=u. Page_load { Con. Return k. } button1_click { It’s me .Int). // to receive the value return by procedure we must make a parameter SQLParameter p1 = new SQLParameter(“@ret”.value). // returnValue is the 4th type of parameter // output parameter can be multiple but we can use only one returnValue. connectionString[“nonu”]. Class_default { SQLConnection con = new SQLConnection.connectionString = configurationManager. if (con.pamameter. cmd. } } Private Int32 checkuser(String u.add(p1).SQLVbType.dispose().open() cmd.

text = ”wrong Password”.1 o Repeator o Data list o Data grid Five type of Composite databound control are there in version 2.0 • • • • • It’s me .Int32 r = checkUser(Textbox1.text).text = ”LOGIN”. } Else { Label1. Textbox2. If ( r = = -1) { Label1. Total 10 templates are there o Item template o Header template o Footer template o Select template o Pager template o Edit item template o Separator template o Alternating item template o Insert item template o Empty data template Last two were added in version 2.37 - .1 and in 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.0 two more are added.text. } } // 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. } Else if ( r = = -2) { Label1.text = “ WRONG USER”.

EventArgs e) { repBind().38 - . update. It’s me .config file and make connectionString • using System. o From the toolbox  data add a repeater o Add web.SqlClient. } private void repBind() { SqlDataAdapter adp = new SqlDataAdapter("select * from tbbook".ConnectionString).• o Repeator o Data list o Grid view o Form view o Detail view All Composite databound control work with templates & vice versa Repeater • • • • • To display data in single column No manipulation (data edit.ConnectionStrings ["cs"]. protected void Page_Load(object sender.Data. delete nahi hota) No paging No default template We can only apply 5 type of template o Item template o Header template o Footer template o Separator template o Insert item template Repeater disconnected approach o Create a database dbbook o 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.ConfigurationManager.

Fill(ds). It implicit open & close the Connection DataSet ds = new DataSet(). /* DataSet • • • • • Collection of table Equal to DataReader We can set the relations Very important point is that it read and write data in XML format Types o Type DataSet  We define the structure at design time  Performance is better than untype DataSet  We use it in reports or when we know fixed no.// SqlDataAdapter always used with disconnection approach. Repeater1. put data in DataSet close connection Repeater1.DataSource = ds. // Fill  create connection.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 /> It’s me . open it. execute query.39 - .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. } • Go to HTML of default.DataBind(). of columns  Extension  .

DISPLAY DATA IN TABLE FORM: Default.<b>Publisher: </b><% #Eval("bookPub")%><br /> <b>Price: </b><% #Eval("bookPrice")%><br /> </td> </tr> </table> </ItemTemplate> </asp:Repeater> Q.aspx <asp:Repeater ID="Repeater1" runat="server"> <HeaderTemplate> <table> <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> It’s me .40 - .

cs protected void Page_Load(object sender. o It will run again n again according to the number of rows. } public Int32 CalDis(Int32 prc) { return prc * 10 / 100.41 - . } private void RepBind() { SqlDataAdapter adp = new SqlDataAdapter("select * from bbook". adp. Header template o It will run only once for heading o It’s the first template. } Template • • • • Working and time of all the template are fixed.ConnectionStrings["cs"].CalDis(prc). EventArgs e) { RepBind(). In item template o We define only single row display format. Order doesn’t disturb the working of templates. which will run. ConfigurationManager. It’s me .DataSource = ds.aspx. DataSet ds = new DataSet().ConnectionString). Repeater1.DataBind(). Repeater1.<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. } public Int32 CalAmt(Int32 prc) { return prc .ToInt32(Eval("bookPrice"))) %> </td> </tr> </AlternatingItemTemplate> </asp:Repeater> Default.Fill(ds).

DISPLAY DATA IN DIFFERENT COLUMN • • Place dataList from toolbox Add web config file and make connection string. Datalist • • • • • To display data in multiple column.isPostBack==false) It’s me . Alternating item templates work with item templates alternating.ConnectionStrings["cs"]. adp.DataBind(). ConfigurationManager. } Page_load { If(page. No default template 7 templates are applicable o Item template o Header template o Footer template o Select template o Edit item template o Separator template o Alternating item template Q.ConnectionString).Data. DataList1.Sqlclient. update) No paging. Private void ListBind() { SqlDataAdapter adp = new SqlDataAdapter("select * from tbbook".42 - . Repeater me different column wala concept nahi hota. DataSet ds = new DataSet().DataSource = ds. Using System. We can manipulate data (edit. delete. DataList1.Fill(ds).• • • • Footer templates will run in the last We can excess only public and protected member in HTML.

0. • • <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/> It’s me .0.43 - . not used with DataList) o Insert (added in version 2. } • 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> • There are some predefine command name o Edit o Update o Delete o Cancel o Select o New (added in version 2. not used with DataList) DataList  property RepeatColumn = Value To display data in more than one column To auto format click on DataList Tasks  AutoFormat.ListBind().

FindControl(“t1”))).Item.ItemIndex]). con. bid = Convert.EditItemIndex = e.ToInt32 (DataList1.Item.FindControl(“t4”))). Int32 prc.text. e) { DataList1. ListBind().text.Item. Pub =((textbox)(e.Item.FindControl(“t2”))). pub. } DataList1_CancelCommand(source.DataKeys[e.FindControl(“t3”))). } DataList1_UpdateCommand(source.text). author.text. Prc=Convert. Title=((textbox)(e.EditItemIndex = -1.ConnectionString = ConfigurationManager. Author =((textbox)(e. e) { String title.<b>Price:</b> <asp:TextBox ID=”t1” Text=’<%#Eval(“bookPrice”)%>’ Runat=”server”> </asp:TextBox><br/> <asp:LinkButton ID=”lb” Text=”Update” CommandName=”Update” Runat=”server”> </asp:LinkButton> <asp:LinkButton ID=”lb” Text=”Cancel” CommandName=”Cancel” Runat=”server”> </asp:LinkButton> </EditItemTemplate> • To make event DataList properties icon(event) EditCommand(double click) DataList properties icon(event) CancelCommand(double click) DataList1_EditCommand(source. It’s me .ToInt32(((textbox) (e. e) { DataList1. SqlConnection con = new SqlConnection().Item.ItemIndex.Item.44 - . // e is current selected item ListBind().

• } To make direct connection with database without coding we use SqlDataSource o It is used with 2 – tier architecture o Two layers in 2 – tier architecture are  Data Access Layer  Presentation Layer o Used for database connectivity. 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. SqlDbType. cmd.VarChar. cmd. cmd.Add("pub".Value = prc.Value = title. DataList1. cmd.Value = pub. 50).Parameters. Click on DataList Tasks  Choose Data Source  SqlDataSource1.Parameters.Add("author".Connection = con. cmd. 50).Add("bid".VarChar.Parameters. ListBind(). bookPub=@pub. 50).Value=author. SqlDbType.EditItemIndex = -1.Dispose().Int).VarChar. cmd.Parameters. bookPrice=@prc where bookId=@bid". 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 • • • • • • It’s me .Add("title".Open(). bookAuthor =@author. cmd. SqlDbType.Add("prc".ExecuteNonQuery().CommandText = "update tbbook set bookTitle=@title. } SqlCommand cmd = new SqlCommand(). SqlDbType. update etc. to read.Value = bid. cmd.config file) Select table  then select columns  then click finish.ConnectionStrings["cs"].Closed) { con. SqlDbType.45 - . if (con.Parameters. insert.State == ConnectionState.Int).ConnectionString. cmd.

DataBind(). e) It’s me .<ItemTemplate> <b>Name:</b><%#Eval("productName")%><br /> <b>Price:</b><%#Eval("unitPrice")%><br /> <b>CategoryId:</b><%#Eval("categoryId")%><br /> <b>SupplierId:</b><%#Eval("supplierId")%><br /> <asp:LinkButton ID="lb" Text=Edit CommandName="edit" runat=server> </asp:LinkButton><br /><br /> </ItemTemplate> <EditItemTemplate> <b>Name:</b><asp:TextBox ID="tb1" Text='<%#Eval ("productName")%>' runat=server></asp:TextBox><br /> <b>Price:</b><asp:TextBox ID="tb2" Text='<%#Eval ("unitPrice")%>' runat=server></asp:TextBox><br /> <b>Category:</b> <asp:DropDownList ID="dd1" DataTextField="categoryName" DataValueField="CategoryId" DataSourceID="SqlDataSource2" runat=server SelectedValue='<%#Eval("categoryId")%>'> </asp:DropDownList><br /> <b>Supplier:</b> <asp:DropDownList ID="dd2" DataTextField="companyName" DataValueField="supplierId" DataSourceID="SqlDataSource3" runat=server SelectedValue='<%#Eval("supplierId")%>'> </asp:DropDownList><br /> <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.46 - .EditItemIndex = e.ItemIndex. DataList1.Item. } DataList1_CancelCommand(source. e) { DataList1.

sd ((DropDownList)(e.Item.Text).Item.{ DataList1. /* • • */ • DataList  Property  DataKeyField  ProductId In this field we mention those field which we don’t want to display but used in programming.EditItemIndex = -1.ToString().DefaultValue=cd.DefaultValue=pn. SqlDataSource1.FindControl("t1"))). Datalist1. prc.FindControl("t2"))).47 - .UpdateParameter[“pid”]. DataKeys Array[0]  0th row ka productId pd = (DataList1.Text. supplierId=@sid where productId=@pid DataList1_UpdateCommand(source.update(). categoryId=@cid.UpdateParameter[“sid”]. pid.item. SqlDataSource1.DefaultValue=pd. pn = ((TextBox)(e.itemIndex]).databind(). SqlDataSource1. sd.DefaultValue=sd.Text.DataBind(). } • SqlDataSource1  Properties  UpdateQuery  Update Products set productname=@pn. SqlDataSource1. e) { String pn.EditItemIndex = -1.DataKeys[e. cd = ((DropDownList)(e.Text. Datalist1.DefaultValue=pn. cd.UpdateParameter[“un”]. } It’s me .UpdateParameter[“cid”].FindControl("dd2"))). SqlDataSource1.Item.FindControl("dd1"))). unitprice=@un.Item. prc =((TextBox)(e.UpdateParameter[“pn”]. DataList1. SqlDataSource1.

} DataSet ds = new DataSet(). adp. PRODUCTS WITH CHECKBOX • • Place DataList1.ConnectionStrings["cs"].ConnectionString).DataBind(). ConfigurationManager.Sqlclient.config file. Using System.isPostBack==false) { SqlDataAdapter adp = new SqlDataAdapter("select * from tbbook". Page_load { If(page.48 - . DataList1.DataSource = ds.Fill(ds). It’s me . Button Add web.Data.Q. DataList1. DataList2.

DataSource = ds.49 - . if(c.DataKey[I]. SqlDataAdapter adp = new SqlDataAdapter("select * from products where product In(“+st+”)”).length-1). adp.write(“Hello World”) It’s me . i<DataList. DataSet ds = new DataSet().”.Fill(ds). } St = st.DataBind().ConnectionString). DataList2.) { checkbox c=(checkbox)(Datalist1.Substring(0.checked ==true) st +=DataList1.FindControl(“cb”)). For(int32 i=0.toString() +”.item[I]. ConnectionStrings["cs"]. DataList2.} Button_click { String st=””.item. } • 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

DISPLAY SELECTED DATA IN TEXTBOX • • Place dataList from toolbox Add web config file and make connection string.Fill(ds).DataSource = ds. } It’s me .ConnectionString). DataList1. DataList1.DataBind(). Private void ListBind() { SqlDataAdapter adp = new SqlDataAdapter("select * from tbbook".Q.ConnectionStrings["cs"].Data.50 - . Using System.Sqlclient. DataSet ds = new DataSet(). adp. ConfigurationManager.

ToString(). ConnectionStrings["cs"].Rows[0] ["bookPub"]. We should use properties. SqlDataAdapter adp = new SqlDataAdapter(st. <asp:DataList…> <ItemTemplate> <b>Title: </b><asp:LinkButton ID="lb" Text='<%#Eval("bookTitle")%>' CommandName=”select" runat=server> </asp:LinkButton><br /> It’s me .Tables[0].ToString().isPostBack==false) ListBind(). //TextBox1.Text = ds. //TextBox3.Tables[0].ToString().Rows[0] ["bookPrie"]. DataSet ds = new DataSet().ToString().Text TextBox2.DataKeys[selectedIndex].Text = ds.ConnectionString).ToString().Text=ds. //TextBox2.Rows[0] ["bookAuthor"].ToString().Tables[0].Text = ds. } DataList1_SelectedIndexChanged { String st. st = "select * from tbbook where bookId=" + DataList1.DefaultView[0].51 - . method.Tables[0].Text TextBox3. adp.Rows[0] ["bookTitle"]. = r[0]["bookPub"]. =r[0]["bookAuthor"].ToString().Page_load { If(page.Fill(ds). // DS is an object n is very heary so it’s not good to call it again n again.Text TextBox4. r=ds. variable but not objects DataRowView r.ToString(). TextBox1. // DataRowView class only accept single row.Text } • In HTML = r[0]["bookTitle"].ToString(). //TextBox4.Tables[0]. ConfigurationManager. = r[0]["bookPrice"].

<b>Author: </b><%#Eval("bookAuthor")%><br /> <b>Publisher: </b><%#Eval("bookPub")%><br /> <b>Price: </b><%#Eval("bookPrice")%><br /> </ItemTemplate> Q.visibility:hidden} </style> <script language='javascript'> function getData(id) { var e. It’s me .52 - .xyz{display:none. 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 > .font-weight:bold} .abc{font-size:larger.

style.getElementById('d'+i).i++) { if(i==id) { i++. e. if(e1) { e1.i<6.display='block'. } for(var i=0.i++) { if(i==id) { i++. e1=document.visibility='visible'.style. It’s me .display='none'.visibility='hidden'.visibility='hidden'.i<6. if(e1) { e1.getElementById('d'+id). } } for(var i=0.color(id).53 - . } else { e. e1.color='black'.display='none'.style. e=document.getElementById('h'+id).style.color='blue'. if(e) { if( } } } function color(id) { var e1. } e2=document. } var e1=document. if(e2) { e2.getElementById('h'+i).display!='block') { e.

Eval (Container.Eval(Container. Q.} } } </script> <asp:Repeater ID="Repeater1" runat="server"> <ItemTemplate> <div id='h<%#DataBinder. block  expand GetElementById in JavaScript is just like FindControl to find the control."itemindex")%>' ondblclick= 'getData(<%#DataBinder."itemindex")%>)' > <b><%#Eval("bookTitle")%><br /></b> </div> <div id='d<%#DataBinder."itemindex")%>)' class='abc' onclick='color(<%#DataBinder. o The cursor which stores the result of select is called implicit cursor. We use cursor in this which are o Private area to SQL o Store Result of query o Information in cursor is called Data set.54 - ."itemindex")%>' class='xyz'> <b> Author:</b><%#Eval("bookAuthor")%><br /> <b> Publisher:</b><%#Eval("bookPub")%><br /> <b> Price:</b><%#Eval("bookPrice")%><br /><br /> </div> </ItemTemplate> </asp:Repeater> • • • Div is a container in which we store different things In Style o Display : none  collapse. Cursor has 4 steps: o Create o Open o Fetch o Close • ALTER PROCEDURE dbo.Eval(Container. PAGING • • Create a store procedure in database.Eval(Container.StoredProcedure1 ( It’s me .

@pagenumber int.55 - .IsPostBack == false) { PageBind(1).categoryId = a. tbcategory b where a. @pagesize int ) AS declare declare declare declare declare @strec int @endrec int @stpid int @endpid int @reccount int set @strec = @pagenumber*@pagesize-@pagesize+1 declare c_prd scroll cursor for select productId from tbproduct order by productId open c_prd fetch 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 if @reccount < @pagesize begin set @endrec = @strec + @reccount end else begin set @endrec = @pagenumber * @pagesize end fetch absolute @endrec from c_prd into @endpid close c_prd select count(*) from tbproduct select productName. e) { if (Page.cs protected void Page_Load(sender. unitPrice.categoryId and productId > @stpid and productId <= @endpid Default. categoryName from tbproduct a. } It’s me .aspx.

} else { repcol = Convert. Label2.} private void PageBind(Int32 pg) { Int32 nor.RepeatColumns = repcol.ExecuteReader(). SqlDataReader dr.56 - . dr = cmd. SqlCommand cmd = new SqlCommand().ConnectionString=ConfigurationManager.SqlDbType.Text = pg.ToInt32(nor / 2). if (nor <= 4) { repcol = nor. dr. con.Read(). SqlConnection con = new SqlConnection(). cmd.Parameters.Add("@pagesize". SqlDbType. cmd. } DataList1. if (total % nor == 0) { t = Convert. cmd.Int). Int32 total.ToInt32(total / nor +1).Open().ToString(). Label3. nor = (Convert. Int32 i. It’s me . } Label1.ConnectionString.Int).StoredProcedure.ToInt32(total / nor).Value=pg.Add("@pagenumber".Parameters.ToInt32(dr[0]). } else { t = Convert.Text = t.ToInt32(DropDownList1. cmd. repcol. cmd.Connection = con.CommandType = CommandType. ArrayList arr = new ArrayList(). total = Convert.SelectedValue)).Value = nor.CommandText = "paging". ConnectionStrings["cs"].ToString().t. con.Text = "of".

true. e) //previous { It’s me . e) { PageBind(1). DataList1.ToInt32(Label3.Enabled = false. if (pg == 1) { Button1.ToInt32(Label3.ToString()).Dispose().Enabled Button3.Enabled = false. } if (pg == Convert.Add("<"). Button2. i <= Convert. Button1. for (i = 1. i++) { arr.57 - .Add(i. DataList2.DataSource = dr.Text)) { Button3. DataList2.Text).DataBind(). true. DataList2.Enabled = false.Horizontal. } protected void Button1_Click(sender.Add(">").Enabled = false.Enabled Button2.Close().DataSource = arr.Enabled = = = = true. cmd. if (dr. true.Enabled Button4.arr.RepeatDirection=RepeatDirection. } protected void Button2_Click(sender. } dr.NextResult()) { DataList1.DataBind(). e) //First { PageBind(1). Button4. } } DropDownList1_SelectedIndexChanged(sender. } arr.

ToInt32(Label3. } void DataList2_SelectedIndexChanged(sender.1). } protected void Button4_Click(sender. } } else { PageBind(DataList2.SelectedIndex==0) { if ((Convert.ToInt32(Label1. } protected void Button3_Click(sender.Items.Text) .ToInt32(Label1.1).Count-1)) { if((Convert.ToInt32(Label1. e) //Next { PageBind(Convert.2)) { PageBind(Convert.Text) + 1).PageBind(Convert.SelectedIndex==DataList2.ToInt32(Label1.Items.e) { if (DataList2.Text))!= 1) { PageBind(Convert.Text))!=(DataList2.Text)). e) //Last { PageBind(Convert. } } else if(DataList2.ToInt32(Label1.ToInt32(Label1.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> It’s me .Text) + 1).58 - .Text) .Count .

We can manipulate data (edit. delete. delete.<asp:DataList ID="DataList2" runat="server"> <ItemTemplate> <asp:LinkButton ID="lb" Text='<%#Container.DataItem%>' CommandName="select" runat="server"> </asp:LinkButton> </ItemTemplate> </asp:DataList> GRIDVIEW • • • • • • • To display data in rows & columns.59 - . Auto edit. select Inbuilt paging Inbuilt sorting Column bound 8 templates are applicable o Item template o Header template o Footer template o Select template o Pager template o Edit item template o Alternating item template o Empty data template It’s me . and update).

SelectedRow. TextBox5.Text = GridView1. e) { TextBox1.Cells[1].Text. TextBox3.Text.Cells[2].• Properties of GridView o AutoGenerateDeleteButton  true o AutoGenerateEditButton  true o AutoGenerateSelectButton  true o AllowPaging  true o PageSize  2 o PagerSetting  Mode  Numeric/NextPrevFirstLast  FirstPageText  First  LastPageText  Last  PrevPageText  Prev  NextPageText  Next  Position  TopBottom/Bottom o AllowSorting  true o Columns  Bookid  properties  Readonly  true o DataKeyNames  bookid // In DataKeyField we can specify only single value but in DataKeyName we can specify more than 1 using “.Text = GridView1. bookAuthor=@bookAuthor.Text = GridView1.SelectedRow.Text.Text.Text = GridView1. TextBox4. 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.SelectedRow. TextBox2.Cells[4].Text = GridView1.” Properties of SqlDataSource o UpdateQuery  update tbbook set bookTitle=@bookTitle.Cells[3]. EventArgs e) { if (Page.IsPostBack == false) { It’s me . } With Coding Page_Load(object sender. bookPub=@bookPub.60 - .SelectedRow.Text.Cells[5].SelectedRow.

GrdBind().Add("@price".FindControl("l"))).EditIndex = -1.RowIndex].Add("@pub". } protected void GridView1_RowEditing(sender.Connection = con. bookPub=@pub.ConnectionString = ConfigurationManager. SqlDbType. GridView1.Rows[e. cmd.Text.Parameters. e) { GridView1.Value = ((TextBox)(GridView1.Text). 50). ConfigurationManager.NewEditIndex. con.Add("@author".RowIndex]. SqlDbType. ConnectionStrings["cs"].Parameters.SqlDbType.FindControl("tb2"))). SqlDbType. cmd.GrdBind(). cmd.DataSource = ds. GridView1. } } private void GrdBind() { SqlDataAdapter adp = new SqlDataAdapter("select * from tbbook".Rows[e.ExecuteNonQuery(). cmd.ConnectionStrings["cs"].SqlDbType.VarChar. cmd.ToInt32 (((TextBox)(GridView1.Parameters. 50).Rows[e. It’s me . e) { GridView1.Value= Convert. cmd.FindControl("tb4"))). 50).ConnectionString.RowIndex].VarChar.61 - .RowIndex].EditIndex = e.FindControl("tb3"))).FindControl("tb1"))).DataBind().Add("@title".Int).Parameters. cmd. bookPrice=@price where bookId=@id". e) { SqlConnection con = new SqlConnection(). cmd.Add("@id". } GridView1_RowCancelingEdit(sender.RowIndex].CommandText ="update tbbook set bookTitle=@title.Value = ((TextBox)(GridView1.Rows[e. GrdBind().ConnectionString).VarChar.Parameters.Text.Int).Fill(ds).bookAuthor= @author.Text).Open().Value=Convert.Value = ((TextBox)(GridView1. adp. con.ToInt32 (((Label)(GridView1. } GridView1_RowUpdating(sender.Rows[e. DataSet ds = new DataSet(). SqlCommand cmd = new SqlCommand().Text.

cmd. cmd.ConnectionString = ConfigurationManager. ConnectionStrings["cs"].62 - . e) { Int32 eno.Connection = con. SqlConnection con = new SqlConnection().EditIndex = -1.RowIndex][0]). } GridView1_RowDeleting(sender. GridView1. cmd.Add("@id". GrdBind().EditIndex = -1.Dispose(). GridView1. cmd.ExecuteNonQuery(). cmd.ToInt32(GridView1. SqlCommand cmd = new SqlCommand().Value= eno. // add DataKeyName in GridView Property eno = Convert.SqlDbType. GrdBind(). con.CommandText="delete from tbbook where bookId=@id". } 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")%> It’s me .Int).Parameters.Open(). con.DataKeys [e.ConnectionString.Dispose().cmd.

</ItemTemplate> <EditItemTemplate> <asp:TextBox ID="tb1" Text='<%#Eval("bookTitle")%>' runat="server"> </asp:TextBox> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Author"> <ItemTemplate> <%#Eval("bookAuthor")%> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="tb2" Text='<%#Eval("bookAuthor")%>' runat="server"> </asp:TextBox> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Publisher"> <ItemTemplate> <%#Eval("bookPub")%> </ItemTemplate> <EditItemTemplate> <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" It’s me .63 - .

GRID WITHIN GRID • • • • • Place Gridview. Add Web Config file. Gridview  property  AutoGenerateColumn  false.64 - .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> </asp:GridView> Q. GridviewpropertyColumnsAdd(TemplateField)HeaderText  Category GridviewpropertyColumnsAdd(TemplateField)HeaderText  Products In HTML <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Height="238px" Width="269px"> It’s me .

adp. EventArgs e) { GrdBind().Web. ConfigurationManager.Fill(ds). It’s me .ConnectionString).<Columns> <asp:TemplateField HeaderText="Category"> <ItemTemplate> <b>ID:</b><%#Eval("categoryId")%><br /> <b>Name:</b>&nbsp.ToInt32(Eval("categoryId")))%>'> <Columns> <asp:BoundField HeaderText="ID" DataField="productId" /> <asp:BoundField HeaderText="Name" DataField="productName" /> <asp:BoundField HeaderText="Price" DataField="unitPrice" /> </Columns> </asp:GridView> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> public partial class _Default : System. ConnectionStrings["cs"].65 - .UI. DataSet ds = new DataSet().Page { protected void Page_Load(object * from tbproduct". <%#Eval("categoryName")%> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Products"> <ItemTemplate> <asp:GridView ID="gv1" AutoGenerateColumns="false" Width="500px" runat="server" DataSource='<%#GetData (Convert. } private void GrdBind() { SqlDataAdapter adp = new SqlDataAdapter("select * from tbcategory.

Web. ConnectionStrings["cs"]. adp. } } • In this query will execute many time and this will lead to poor performance Another way public partial class _Default : System. GridView1.ConnectionString). GridView1. // DataView is used to store.ToString().DataBind(). It is temperory file on client side. GridView1. Navigate data.ConfigurationManager. DataSet ds = new DataSet(). dv. } public DataSet GetData(Int32 cid) { String st. return (ds).DataSource = ds.UI. protected void Page_Load(object sender.DataSource = ds.Fill(ds).RowFilter = "categoryId=" + cid.66 - . filter.DefaultView. ConnectionStrings["cs"].Tables[0]. return dv.ConnectionString). } private void GrdBind() { SqlDataAdapter adp = new SqlDataAdapter("select * from tbcategory. ConfigurationManager.GridView1.DataBind(). st="select * from tbproduct where catergoryId=" * from tbproduct". EventArgs e) { GrdBind(). } public DataView GetData(Int32 cid) { DataView dv = ds. } } It’s me .ToString().Page { DataSet ds = new DataSet(). SqlDataAdapter adp= new SqlDataAdapter(st.Tables[1].

EventArgs e) { GrdBind().Data. GRAND AND SUBTOTAL using System. } private void GrdBind() { It’s me . using System.67 - .UI.Drawing.SqlClient.Q. public partial class _Default : System.Web.Page { protected void Page_Load(object sender.

e) { //Event in gridview which is called for all the rows for all templates. GridView1. } DataRow r1.Tables[0].Rows.Tables[0].Tables[0].sum(unitsinstock) unitsinstock from products a. DataRow r.ConfigurationManager. DataSet ds = new DataSet(). r1[1] = "G. } It’s me . r[1] = pc. r = ds.categoryId group by categoryname.Rows[i].Rows. adp. String pc = "". ConnectionStrings["cs"]. GridView1.String st.DataSource = ds. } protected void GridView1_RowDataBound(sender.InsertAt(r. r[2] = -1. productname with rollup". String nc = "". i++. ds.categoryId=b.Tables[0]. if (e. while (i < ds. SqlDataAdapter adp=new SqlDataAdapter(st.Tables[0]. i). st = "select case when(grouping(categoryname)=1) then 'G.Rows[i][0]. Int32 i=0. } i++.ConnectionString).NewRow().case when (grouping(productname)=1) then 'Sub Total' else productname end productname.Count-1) { nc = ds.DataBind().Total' else categoryname end categoryname .ToString().68 - . categories b where a.Fill(ds).Row.Total". sum(unitprice) unitprice.Gray.Cells[0]. r1 = ds.Text == "Sub Total") { e. if (nc != pc) { pc = nc.BackColor = Color.Row.

} } } QUERY ANALYZER select isnull (categoryname. } if (e.Row.sum(unitsinstock) unitsinstock from products a. e.Row.BackColor = Color.Cells.Chocolate. } if (e.Row.Cells[0].69 - . categories b where a.Row.Chocolate.Row.Cells[0].Cells[0].Row.Text == "-1") { e.categoryId=b. e.ColumnSpan = 3.'G.Text == "G.Cells.HorizontalAlign = HorizontalAlign.Cells[0]. e. sum(unitprice) unitprice.Toatal').BackColor = Color.if (e. e.Cells[1].Row. 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.BackColor = Color.categoryId group by categoryname.RemoveAt(1).Row.Row. It’s me .Center.Font.Bold = true. e.Row.'Sub Total').Row.RemoveAt(2).Pink.Cells[0].Text == "Name") { e.Total") { e.isnull (productname.

categoryId group by categoryname. 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.sum(unitsinstock) unitsinstock from products a.categoryId=b. categories b where a. productname with rollup Q. sum(unitprice) unitprice.Total' else categoryname end categoryname. It’s me .case when(grouping(productname)=1) then 'Sub Total' else productname end productname.categoryId=b. categories b where a. sum(unitprice) unitprice.sum(unitsinstock) unitsinstock from products.categoryId group by categoryname.70 - . productname with rollup a.*********************************************************************** * select case when(grouping(categoryname)=1) then 'G.

} protected void GridView1_RowCommand(sender.ToInt32(((TextBox) (GridView1.Open().SqlClient.UI. DataSet ds = new DataSet().Text). } SqlCommand cmd = new SqlCommand(). con.Page { SqlConnection con = new SqlConnection(). es.Text.FooterRow.IsPostBack) { GrdBind().Closed) { con. GridView1. eno= Convert. It’s me .Text).FooterRow.Fill(ds).Web. EventArgs e) { if (!Page.CommandName == Save) { Int32 eno.ConnectionString.ToInt32(((Label) (GridView1. GridView1.Data. en = ((TextBox) (GridView1. eadd. public partial class _Default : System. if (con.• When we mention command name of our choice then that is come under RowCommand event using System.FindControl("textbox4"))).FooterRow.DataSource = ds.Text.FindControl("textbox2"))). e) { if (e. eadd = ((TextBox) (GridView1.DataBind(). protected void Page_Load(object sender.FindControl("textbox6"))).State == ConnectionState. ConfigurationManager. ConnectionStrings["cs"].ConnectionString). adp.71 - . } } private void GrdBind() { SqlDataAdapter adp = new SqlDataAdapter("select * from tbemp". es= Convert. String en.FooterRow.FindControl("label3"))).ConnectionString = ConfigurationManager.ConnectionStrings["cs"].

} } public Int32 AutoGen() { SqlCommand cmd = new SqlCommand(). GrdBind().Parameters.Parameters.VarChar. if (con. } cmd. ConnectionStrings["cs"]. // add DataKeyName in GridView Property eno = Convert.Connection = con. } protected void GridView1_RowEditing(sender.Value = es.Add("@es".Value=en.@es)".Connection = con.ExecuteNonQuery().Open().50).Parameters. 0) from tbemp".Add("@eno". Int32 r = Convert.State==ConnectionState. cmd. It’s me .e) { GridView1. SqlDbType.@en.Add("@en".Closed) { con. GrdBind().Int).cmd. cmd. if (con. ConnectionStrings["cs"].ToInt32(cmd.NewEditIndex. e) { Int32 eno. SqlDbType.ConnectionString = ConfigurationManager.DataKeys [e.ToInt32(GridView1.CommandText = "insert into tbemp values(@eno.ConnectionString = ConfigurationManager.Value=eadd. return r.CommandText = "select isNull(max(empno). cmd.Parameters.Int).Dispose().Open().State == ConnectionState.ExecuteScalar())+ 1.@eadd. .RowIndex][0]).Closed) { con.Dispose(). cmd.ConnectionString. cmd. // we can also use adp. con.ConnectionString.VarChar. SqlDbType.Add("@eadd".EditIndex = e.72 - con. cmd. SqlDbType. } protected void GridView1_RowDeleting(sender.Value=eno. cmd. 50).insertCommand = cmd cmd. cmd.

cmd. cmd.Text.RowIndex].RowIndex]. SqlDbType. cmd.Rows [e. eaddress=@eadd. con.Value=eadd.Value = en. cmd.Value=eno. cmd.50). es. } protected void GridView1_RowUpdating(sender.EditIndex = -1. cmd. if (con. SqlDbType. eno = Convert. } protected void GridView1_RowCancelingEdit(sender. eadd = ((TextBox)(GridView1.Value = eno.Parameters.Text. e) { Int32 eno. cmd.ConnectionString = ConfigurationManager.State == ConnectionState. e) { GridView1.RowIndex].Add("@en".ConnectionString.Int). String en.Connection = con.Value = es.ExecuteNonQuery().Rows[e.Int). 50). en = ((TextBox)(GridView1. } SqlCommand cmd = new SqlCommand(). SqlDbType. cmd.ExecuteNonQuery(). GrdBind(). esal=@es where empno=@eno".ToInt32(((TextBox) (GridView1.Parameters. eadd.Text). It’s me .Int).RowIndex].Rows[e. SqlDbType.Parameters.ToInt32(((Label)(GridView1.Parameters. GridView1.CommandText = "update tbemp set ename=@en.Add("@eadd".FindControl("textbox1"))).Add("@eno". cmd.Add("@es".Text). FindControl("textbox5"))).Dispose(). cmd. ConnectionStrings["cs"].} SqlCommand cmd = new SqlCommand(). SqlDbType.73 - .Dispose(). es = Convert.VarChar.VarChar.EditIndex = -1. FindControl("textbox3"))).Add("@eno".Closed) { con.CommandText = "delete from tbemp where empno=@eno". FindControl("label2"))).Open(). GrdBind(). cmd.Parameters.Rows[e. cmd. cmd.Connection = con.

} } Q.74 - .GrdBind(). GridView (properties)ColumnsCommandFieldadd Selectproperties Visible = false It’s me . TO DISPLAY DATA IN TEXTBOX JUST CLICKING ON ROW • • • Place Gridview chose data source Place SQLDataSource and configure it.

Row.SelectedRow. TextBox4.Cells[2].RowType == DataControlRowType. e) { if (e.RowType == DataControlRowType.Cells[3].Footer) { } else { LinkButton lk = (LinkButton)(e.Data. TO SELECT COLUMNS TO BE DISPLAY AT RUN TIME • • • • Place Gridview Add web config file Place CheckBox list Place button using System.SelectedRow.Cells[0].Controls[0]).. TextBox2.Text = GridView1.SqlClient.Cells[4].. e.Attributes["onClick"] = ClientScript.Cells[1].Text = GridView1.Row. GetPostBackClientHyperlink(lk.Row.protected void GridView1_RowDataBound(sender. } } protected void GridView1_SelectedIndexChanged(sender.Text.Cells[6].SelectedRow.e) { TextBox1.Text.Row.Text.Text = GridView1.%> Q. TextBox5.SelectedRow.Text = GridView1.SelectedRow.Text.75 - .Text = GridView1.Header) { } else if (e. } In HTML <%@ Page Language="C#" EnableEventValidation="false". It’s me .Text. TextBox3. "").

".76 - . i < CheckBoxList1.Add(dr. SqlDataAdapter adp=new SqlDataAdapter(st1. String st1 = "select " + st + " from tbbook".ConnectionStrings["cs"].ConnectionString).GetName(i). for (i = 0.UI.public partial class _Default : System. SqlDataReader dr = cmd.ExecuteReader(). con.Items[i]. con.DataBind(). // to get the value of that column we can use GetValue } } } protected void Button1_Click(sender.Count.Connection = con.Items[i].Fill(ds). GridView1. } } It’s me .1).ConnectionString = ConfigurationManager. i < dr.Selected == true) { st += CheckBoxList1.FieldCount.ToString()). i++) { CheckBoxList1. Int32 i. for (i = 0.Configuration Manager.DataSource = ds. SqlCommand cmd = new SqlCommand(). DataSet ds = new DataSet(). cmd. st. } } st = st. EventArgs e) { String st = "".Text + ".CommandText = "select * from tbbook".ConnectionString. EventArgs e) { if(!Page.Items. adp. i++) { if (CheckBoxList1. Int32 i.Page { protected void Page_Load(object sender.Open().Substring(0.Length . cmd.IsPostBack) { SqlConnection con = new SqlConnection().Web. GridView1. ConnectionStrings["cs"].Items.

delete.77 - . insert We display fields in rows but in gridview we display fields in columns In this there is AutoGenrateRow Command name o Edit It’s me .DETAILVIEW • • • • • • • Similar to GridView we can display only single record In built paging Auto editing.

@ename. Place DetailView.UpdateParameters["es"].UpdateParameters["eno"]. bookAuthor=@bookAuthor.@eaddress.Controls[0])).Keys[0].UpdateParameters["ed"].NewValues[3].78 - .NewValues[2]. e) { SqlDataSource1.Cells[1]. It’s me .DefaultValue = e.ToString().@esal) • • If parameter name are different from columns name DetailsView1_ItemUpdating(sender.Text. /* whenever we use update then two arrays are make one contaning old values other with new values.DefaultValue = e.DefaultValue=((TextBox) (DetailsView1. SqlDataSource1.DefaultValue = e. bookPrice=@bookPrice where bookId=@bookId o DeleteQuery  Delete from tbbook where bookId=@bookId o InsertQuery  Insert into tbemp values(@empno.• • • o Update o Cancel o Delete o New o Insert We use Detail view for single record operation . SqlDataSource1.UpdateParameters["eno"].ToString().NewValues[1]. bookPub=@bookPub. //Another way //SqlDataSource1.ToString().DefaultValue = e. In we refer to array with values as NewValues[ ]*/ SqlDataSource1.UpdateParameters["en"].ToString(). SqlDataSource and configure them Properties of DetailView o AutoGenerateDeleteButton  true o AutoGenerateEditButton  true o AutoGenerateInsertButton  true o AllowPaging  true o DataKeyNames  bookid Properties of SqlDataSource o UpdateQuery  update tbbook set bookTitle=@bookTitle.Rows[0].

Rows[0].Cells[1].DefaultValue=((TextBox) (DetailsView1.Rows[2].Keys[0].Cells[1].DefaultValue= e.InsertParameters["ed"].Text.DefaultValue=((TextBox) (DetailsView1.DefaultValue=((TextBox) (DetailsView1.Controls[0])).Rows[3].InsertParameters["eno"].UpdateParameters["eno"].Text.Controls[0])). e) { SqlDataSource1.Cells[1].Text.} DetailsView1_ItemInserting(sender.ToString(). SqlDataSource1.79 - .Controls[0])).Controls[0])). SqlDataSource1.Text.Cells[1]. e) { SqlDataSource1. } DETAIL VEIW WITH CODING • • • • Place DetailVeiw Add Web Config File DetailVeiw  properties  AutoGenrateRows  false DetailVeiw  properties  fields  Add template fields o Empno It’s me .InsertParameters["es"].InsertParameters["en"]. } DetailsView1_ItemDeleting(sender.Rows[1]. SqlDataSource1.DefaultValue=((TextBox) (DetailsView1.

SqlClient.Page { It’s me .Data.o o o o • Name Address Salary For buttons DetailVeiw  Tasks  Edit Templates o Empno  ItemTempLabelEditDataBinding codeEval(“empno”)  EditItemTemLabelEditDataBinding codeEval(“empno”)  InsertItemTextboxEditDataBinding codeEval(“empno”) o Ename  ItemTempLabelEditDataBinding codeEval(“ename”)  EditItemTemTextboxEditDataBindincodeEval(“ename”)  InsertItemTextboxEditDataBinding codeEval(“ename”) o Eaddress  ItemTempLabelEditDataBinding codeEval(“eadd”)  EditItemTemTextBoxEditDataBinding codeEval(“eadd”)  InsertItemTextboxEditDataBinding codeEval(“eadd”) o Esal  ItemTempLabelEditDataBinding codeEval(“esal”)  EditItemTemTextboxEditDataBinding codeEval(“esal”)  InsertItemTextboxEditDataBinding codeEval(“esal”) o Buttons  ItemTemp LinkButtons Edit (CommandName  edit) New (CommandName  new) Delete(CommandName  delete)  EditItemTemTextboxEditDataBinding codeEval(“esal”) Update (CommandName  update) Cancel (CommandName Cancel) o InsertItemTextboxEditDataBinding codeEval(“esal”) Save (CommandName Insert) Cancel (CommandName  Cancel) Empty Data Template //To show table if no data available  ItemTemp LinkButtons Add Data to Table (CommandName new)  using System.80 - .UI. public partial class _Default : System.Web.

ConnectionStrings["cs"].ChangeMode(DetailsViewMode.IsPostBack) { DetailBind().81 - .ChangeMode(DetailsViewMode. } protected void DetailsView1_ItemDeleting(sender. ConfigurationManager.protected void Page_Load(object sender.DataBind().Insert) { DetailsView1.Edit).Insert). Rows[0].NewMode == DetailsViewMode. EventArgs e) { if (!Page. } } private void DetailBind() { SqlDataAdapter adp = new SqlDataAdapter("select * from tbemp". adp.Edit) { DetailsView1. e) { if (e.Fill(ds). // for InsertItemTemplate } else { DetailsView1. DataSet ds = new DataSet().NewMode == DetailsViewMode. e) { Int32 eno.ChangeMode(DetailsViewMode. // for EditItemTemplate } else if (e. It’s me . DetailsView1.ConnectionString).Text).FindControl("label1"))). // for ItemTemplate } DetailBind(). } protected void DetailsView1_ModeChanging(sender.DataSource = ds.ReadOnly). eno = Convert. DetailsView1.ToInt32(((Label)(DetailsView1.

50). DetailBind(). cmd. cmd. cmd.Value = es. FindControl("textbox5"))).Dispose(). cmd.ConnectionString = ConfigurationManager. ed.Value=en.Text.Parameters.@es)". SqlDbType.Parameters.Rows[1].Text). e) { Int32 eno. cmd.Int).Text.ToInt32(((TextBox)(DetailsView1.ToInt32(((TextBox)(DetailsView1.ExecuteNonQuery(). con. cmd.CommandText = "delete from tbemp where empno=@eno". con.Text). cmd.Add("@en". ConnectionStrings["cs"].Parameters.VarChar.@ed. ConnectionStrings["cs"].Value = eno.Add("@eno".Parameters.82 - .Add("@eno".SqlDbType. cmd.FindControl("textbox1"))).VarChar.Rows[2]. 50).Value = eno. Rows[0]. String en.Int). cmd. ed = ((TextBox)(DetailsView1.@en.Parameters. es.CommandText = "insert into tbemp values(@eno. SqlConnection con = new SqlConnection(). con.ConnectionString = ConfigurationManager. cmd.Add("@es". cmd.ConnectionString.SqlDbType.Add("@ed". FindControl("textbox7"))). SqlCommand cmd = new SqlCommand().SqlConnection con = new SqlConnection(). en = ((TextBox)(DetailsView1.ConnectionString. SqlDbType.Int).Open().Value= ed. cmd.Connection = con.Connection = con. es = Convert. } protected void DetailsView1_ItemInserting(Sender. SqlDbType.Open().Rows[3]. It’s me .ExecuteNonQuery(). FindControl("textbox3"))). con. SqlCommand cmd = new SqlCommand(). eno = Convert.

cmd. } } Q.Open(). } protected void DetailsView1_ItemUpdating(sender. cmd.ExecuteNonQuery(). eno = Convert.ReadOnly). en = ((TextBox)(DetailsView1.Value = eno.Parameters. es = Convert.Value = es. TO SELECT PRODUCT TO SEE THE DETAILS • Place Drop Down List o choose data source  SqlDataSource1 It’s me .50).SqlDbType. SqlCommand cmd = new SqlCommand(). ed.SqlDbType.Text).VarChar.Rows[3].ConnectionString.NewPageIndex.Connection = con. con.SqlDbType. cmd. e) { DetailsView1.Text.SqlDbType.Value=ed. ConnectionStrings["cs"].Add("@eno".ChangeMode(DetailsViewMode.Dispose().esal=@es where empno=@eno".PageIndex = e.ToInt32(((TextBox)(DetailsView1.Rows[0].Add("@en".50).CommandText = "update tbemp set ename=@en. } protected void DetailsView1_PageIndexChanging(sender.Dispose(). e) { Int32 eno. String en.ConnectionString = ConfigurationManager.ReadOnly).Value=en.ChangeMode(DetailsViewMode. ed = ((TextBox)(DetailsView1. DetailsView1.Rows[2].Parameters.Rows[1]. DetailBind(). es.cmd.Add("@ed". FindControl("label2"))). SqlConnection con = new SqlConnection(). FindControl("textbox6"))).Text). cmd.Int). FindControl("textbox4"))). eaddress=@ed. cmd. cmd.ToInt32(((Label)(DetailsView1.VarChar. cmd.Parameters. cmd. con. DetailsView1.Text. FindControl("textbox2"))). DetailBind().Parameters.Int). DetailBind().83 - .Add("@es".

• • • • o Enable PostBack Place Grid View o choose data source  SqlDataSource2 o Enable Select button Place Detail View o choose data source  SqlDataSource3 Add SqlDataSource1 o In “NorthWind” database chose “categories” table in which select “categoryId”. TO SELECT PRODUCT TO PURCHASE AND CHECK DETAIL • Place Drop Down List It’s me .”UnitPrice” columns o Click on where button set Column  CategoryId Operator  = Source  Control ControlId  DropDownList o Click on add button Add SqlDataSource3 o In “NorthWind” database chose “Product” table in which select “*” columns o Click on where button set Column  ProductId Operator  = Source  Control ControlId  GridView o Click on add button • Q. “categoryName” columns Add SqlDataSource2 o In “NorthWind” database chose “Product” table in which select “ProductId”. “ProductName”.84 - .

con.DataSource = dr. SqlCommand cmd = new SqlCommand(). SqlConnection con = new SqlConnection(). It’s me .ToString(). Add items to List. GrdBind().Fill(ds).SupplierId=b.ExecuteReader().SqlClient.Web.Dispose().Data.ConnectionStrings["cs"]. } } private void DropDownBind() { this. DropDownList1.Page { protected void Page_Load(object sender.DataSource=ds.SupplierId and CategoryId=" + DropDownList1. dr. con. } private void GrdBind() { cmd. ConnectionString).CategoryId from Categories".85 - . ConfigurationManager.SelectedValue. DropDownList1. Deselect All) using System.DataTextField = "CategoryName". GridView1. DropDownList1.IsPostBack) { DropDownBind(). cmd.DataValueField = "CategoryId".• • • Place GridView1 Place GridView2 Place LinkButtons (Show List. SqlDataAdapter adp=new SqlDataAdapter(st. Select All.SmartNavigation = true.Connection = con.Close().DataBind().CommandText = "Select CategoryName. DropDownList1.Suppliers b where a. String st = "Select * from Products a. DataSet ds = new DataSet(). dr = cmd. cmd.UI.ConnectionString. adp. public partial class _Default : System. ConnectionStrings["cs"].ConnectionString = ConfigurationManager. EventArgs e) { if (!Page.Open(). SqlDataReader dr.

Rows. e) { SqlConnection con1 = new SqlConnection().86 - .DataBind(). i++) { CheckBox cb = (CheckBox)(GridView1. con1. } protected void LinkButton4_Click(sender.GridView1. e) { GrdBind().Rows.Checked == true) { String pn. Int32 p.ConnectionString = ConfigurationManager.Rows[i]. i++) { CheckBox cb = (CheckBox)(GridView1. for (Int32 i = 0. } } protected void LinkButton2_Click(sender.Count. } } protected void LinkButton3_Click(sender.SmartNavigation = true. cmd. cb.ConnectionString.Checked = false. con1. e) { this. FindControl("cb")).Checked = true.Rows[i]. Int32 i. pn =((Label)(GridView1. for (i = 0. e) { this. i++) { CheckBox cb = (CheckBox)(GridView1.Open(). if (cb.Rows[i].Rows[i]. i < GridView1.Rows. ConnectionStrings["cs1"].Connection = con1. } DropDownList1_SelectedIndexChanged( sender. SqlCommand cmd = new SqlCommand(). FindControl("cb")). cb.Count. i < GridView1. for (i = 0.SmartNavigation = true. FindControl("cb")). i < GridView1. Int32 i.Count. It’s me .

CommandName == "Buy") { SqlConnection con1 = new SqlConnection(). SqlDbType. e) { if (e.FindControl("l2"))).ToInt32(((Label)(GridView1.@p"+i+")".CommandText = "delete from tbpurc".Parameters. } } con1. SqlCommand cmd = new SqlCommand().CommandText = "insert into tbpurc values(@pn"+i+". cmd.Value = p.VarChar. cmd.ConnectionString.ExecuteNonQuery().DataSource = ds.FindControl("l1"))). GridView2.DataBind(). cmd.ConnectionString).Fill(ds). 50). p = Convert.ExecuteNonQuery(). It’s me .Value = pn. con1. cmd. e) { GrdBind2(). } private void GrdBind2() { SqlDataAdapter adp = new SqlDataAdapter("select case when( grouping (ProductName)=1) then 'Total' else ProductName end ProductName.Connection = con1.Text.Add("@pn"+i. ConnectionStrings["cs1"]. adp. cmd. SqlDbType. Rows[i]. ConfigurationManager. DataSet ds = new DataSet().ConnectionStrings ["cs1"].Parameters.Int). } } cmd.Dispose().Open().Dispose().ConnectionString = ConfigurationManager.87 - . GridView2. cmd.Text). } protected void GridView2_RowCommand(sender. cmd. } protected void LinkButton1_Click1(sender.Add("@p"+i. cmd. sum(Price) Price from tbpurc group by ProductName with rollup".

88 - .{Display:none.display!='block') { e.display='none'.visibility='hidden'. e. } var e1=document.getElementById('d'+i). } else { e.display='block'.visibility='hidden'. if(e) { if(e.visibility='visible'. if(e1) { e1.i++) { if(i==id) { i++. if(e1) It’s me .style.} In HTML <style type="text/css"> .abc{ } } for(var i=0. e.display='none'.getElementById('d'+id).font-weight:bold} .style. color(id).visibility:hidden} </style> <script type="text/javascript"> function GetData(id) { var e. } } } function color(id) { var<'h'+id).

i++) { if(i==id) { i++. } } } </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" 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> It’s me .color='blue'. } for(var - .color='black'.style.{ e1. if(e2) { e2. } e2=document.getElementById('h'+i).i<12.

"RowIndex")%>' class='xyz' ondblclick='GetData(<%#DataBinder.'> <asp:Label ID="l1" Text='<%#Eval("ProductName")%>' runat="server"> </asp:Label> </div> <div id='d<%#DataBinder.Eval(Container.&nbsp."RowIndex")%>).'> <b>Supplier Name:</b><%#Eval("CompanyName")%><br /> <b>Supplier Address:</b><%#Eval("Address")%><br /> <b>City:</b>&nbsp. Eval(Container."RowIndex")%>).' onclick='color (<%#DataBinder.&nbsp."RowIndex")%>).&nbsp."RowIndex")%>).&nbsp.<%#Eval("city")%><br /> <b>Phone:</b>&nbsp.<div id='h<%#DataBinder."RowIndex")%>' class='abc' ondblclick='GetData (<%#DataBinder.Eval(Container.Eval(Container.90 - . Eval(Container.' onclick='color (<%#DataBinder.<%#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> </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> It’s me .Eval(Container.

91 - .<asp:LinkButton ID="LinkButton5" runat="server" CommandName="Buy">Buy </asp:LinkButton> </FooterTemplate> </asp:TemplateField> </Columns> </asp:GridView> </div> </form> </body> </HTML> FORMVIEW • Similar to DetailView It’s me .

92 - . place LabelEditDataBinding codeEval(“ename”) o Write Eaddress. place TextboxEditDataBinding codeEval(“ename”) o Write Eaddress. place LabelEditDataBinding codeEval(“esal”) o Place LinkButtons Edit (CommandName  edit) New (CommandName  new) Delete(CommandName  delete) EditItemTemplate o Write Empno. place TextboxEditDataBinding codeEval(“esal”) o Place LinkButtons Save (CommandName Insert) Cancel (CommandName  Cancel) It’s me .• • • • • • • • • • • • • • 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. place TextboxEditDataBindincodeEval(“ename”) o Write Esal. place TextboxEditDataBinding codeEval(“esal”) o Place LinkButtons Update (CommandName  update) Cancel (CommandName Cancel) InsertItemTemplate o Write Empno. place LabelEditDataBinding codeEval(“empno”) o Write Ename. No Default Template Command name o Edit o Update o Cancel o Delete o New o Insert We use from view for single record operation . place LabelEditDataBinding codeEval(“empno”) o Write Ename. place TextboxEditDataBinding codeEval(“ename”) o Write Eaddress. place TextboxEditDataBinding codeEval(“empno”) o Write Ename. place LableEditDataBindincodeEval(“ename”) o Write Esal. place TextboxEditDataBindincodeEval(“ename”) o Write Esal. 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.

EventArgs e) { if (!Page.ReadOnly). // for EditItemTemplate } else if (e.ChangeMode(FormViewMode.IsPostBack) { FrmBind(). FormVeiw1. // for ItemTemplate } FormBind().ChangeMode(FormViewMode. } protected void FormView1_ModeChanging(sender.Web.• EmptyDataTemplate //To show table if no data available o Write No Data Available o Add LinkButtons Add Data to Table (CommandName new) using System. DataSet ds = new DataSet().SqlClient.Edit).ChangeMode(FormViewMode.Page { protected void Page_Load(object sender.NewMode == FormViewMode.ConnectionStrings["cs"].NewMode == FormViewMode. } It’s me . public partial class _Default : System. adp. ConfigurationManager. FormView1.Edit) { FormView1.ConnectionString).Data.93 - . e) { if (e.DataBind(). } } private void FrmBind() { SqlDataAdapter adp = new SqlDataAdapter("select * from tbemp".Fill(ds).UI.Insert) { FormView1.DataSource = ds.Insert). // for InsertItemTemplate } else { FormView1.

SqlDbType.Open().Connection = con. SqlCommand cmd = new SqlCommand().Text. FindControl("textbox7"))).Int). con. es.Connection = con. cmd. ed.Add("@es". eno = Convert. ConnectionStrings["cs"]. cmd. cmd. SqlDbType. It’s me . cmd. ed= ((TextBox)(FormView1. String en.Value = eno. con. FormBind().@ed.ConnectionString = ConfigurationManager. eno = Convert. } protected void FormView1_ItemInserting(Sender.Parameters.@en.@es)". es = Convert.Value=en.Text.Parameters.Text). SqlDbType.Add("@eno". cmd.CommandText = "delete from tbemp where empno=@eno".ConnectionString.Int). FindControl("textbox4"))).Text).Parameters.ConnectionString = ConfigurationManager.ToInt32(((TextBox)(FormView1. SqlConnection con = new SqlConnection(). ConnectionStrings["cs"]. con. cmd. cmd.Int).94 - . e) { Int32 eno. SqlCommand cmd = new SqlCommand(). SqlDbType.ConnectionString.protected void FormView1_ItemDeleting(sender.Parameters.Add("@en". 50).FindControl("textbox6"))).ExecuteNonQuery(). cmd. con. en= ((TextBox)(FormView1. e) { Int32 eno.ToInt32(((TextBox)(FormView1.Open().Add("@eno".ToInt32(((Label)(FormView1.Value = eno.Value = es. cmd.Text).CommandText = "insert into tbemp values(@eno.FindControl("textbox5"))).VarChar. SqlConnection con = new SqlConnection(). cmd.Dispose(). FindControl("label1"))).

en=((TextBox)(FormView1.Dispose(). cmd. FindControl("label2"))). cmd.ReadOnly).Add("@ed". eaddress=@ed. SqlCommand cmd = new SqlCommand(). FormBind().Parameters.ConnectionString.Open().SqlDbType.PageIndex = e. FormView1. FormBind(). con. eno = Convert.cmd.Connection = con. } protected void FormView1_ItemUpdating(sender.Parameters. FindControl("textbox3"))).VarChar.95 - .Parameters.ChangeMode(FormViewMode. } protected void FormView1_PageIndexChanging(sender. cmd.ChangeMode(FormViewMode. ConnectionStrings["cs"]. ed=((TextBox)(FormView1. String en.VarChar. cmd.50).CommandText = "update tbemp set ename=@en.Text.ConnectionString = ConfigurationManager.Add("@eno". es.Add("@ed".SqlDbType.SqlDbType. e) { FormView1. FormView1. ed. SqlConnection con = new SqlConnection().Int).Int).Text).NewPageIndex.SqlDbType.50).Parameters.Value = eno.Value = es. cmd.FindControl("textbox2"))).ExecuteNonQuery(). cmd.Add("@es".Parameters.SqlDbType.VarChar.ReadOnly).Value=ed. cmd. } } It’s me .Value= ed.ToInt32(((Label)(FormView1.ExecuteNonQuery().50).Dispose().Text). FormBind(). cmd. con. cmd. es = Convert.ToInt32(((TextBox)(FormView1. e) { Int32 eno. cmd.Value=en.Text.esal=@es where empno=@eno".Add("@en".FindControl("textbox1"))).

DataSource = ds obj.DataBind() End Sub End Class Public Class clsEmp Public eno As Int32 Public en As String Public eadd As String Public es As Int32 ‘ we don’t use public variable we use public properties coz they can be readonly.DataTextField = datatext obj. ByVal datavalue As String) Dim adp As New SqlDataAdapter(qry. ByVal obj As ListControl. validation & checks.SqlClient Imports System.96 - .Data. ByVal datatext As String. "DataBase=dbemp.Configuration Namespace nsEmp Public Class clscomfuntion Public Shared Sub Fill_Data(ByVal qry As String.CLASSES • • • Collection of similar type of data Objects can use each n every members Types: Non compiled classes o Compile with project o Scope within the project Website Add new items  class • Imports System.Data Imports System. ‘ writeonly. for security Public Sub New() ‘ Constructor eno = 11 en = "Sachin" eadd = "Ambala" es = 23000 End Sub It’s me .Fill(ds) obj.DataValueField = datavalue obj.uid=sa") Dim ds As New DataSet adp.

97 - .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 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 It’s me .

eno = 66 obj.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 Class End Namespace • • • Place textbox Place three buttons Place DropDownList Partial Class _Default Inherits System.en = " sachin gupta" obj.disp() End Sub It’s me .Page Button1_Click() Handles = 23007 TextBox1.clsEmp obj.Click Dim obj As New nsEmp.eadd = "Ramnagar" obj.98 - .Web.UI.Text = obj.

p_ctr = 111 error End Sub Page_Load() Handles Me.99 - .p_eadd = "16-17 Ramnagar" obj.p_ctr 'obj.Text = obj.Load nsEmp.Button2_Click() Handles Button2.p_ename = " sachin gupta" obj.p_empno = 66 obj. "empno") End Sub End Class It’s me .disp() End Sub Button3_Click() Handles Button3.Fill_Data("Select * from bemp". "ename".Text = obj.Click Dim obj As New nsEmp.Click Dim obj As New nsEmp.clscomfuntion.clsEmp1 obj.clsEmp2 TextBox1. DropDownList1.p_esal = 23007 TextBox1.

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

It’s me

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

It’s me

- 101 -

End Class End Namespace

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

Imports System.Data.SqlClient Imports System.Data Imports System.Configuration Namespace nsemp Public Interface intcom Sub Save_Rec() Sub Update_Rec() Sub Delete_Rec() Function Find_rec() As DataSet End Interface Public Interface intemp Property p_empno() As Int32 Property p_ename() As String Property p_eadd() As String 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 End Class Public Class clsemp Inherits clscon Implements intcom, intemp 'phele class inherit then implement interface Private Private Private Private eno As Int32 en As String ed As String es As Int32

It’s me

- 102 -

Parameters.Save_Rec If con. SqlDbType.Int).Close() End Sub It’s me . con) adp.VarChar.CommandType = CommandType. con) cmd.Parameters.Add("@en". StoredProcedure Dim ds As New DataSet() adp. SqlDbType.Parameters. SqlDbType.Value = p_empno adp.Value = p_empno cmd.Add("@ed".103 - .SelectCommand. Value = p_eadd cmd.Value = p_empno cmd.CommandType = CommandType. con) cmd.Dispose() con.SqlDbType.Add("@eno".State = ConnectionState. SqlDbType. 50).Add("@es". 50).Data.Parameters.Open() End If Dim cmd As New SqlCommand("insemp".ExecuteNonQuery() cmd.Value = p_esal cmd.CommandType = CommandType. SqlDbType.Closed Then con.Parameters.Dispose() con.DataSet ‘it will open connection and after use close it Dim adp As New SqlDataAdapter("findemp".StoredProcedure cmd.Add("@eno".Int).Add("@eno".Close() End Sub Public Function Find_rec() As System. Value = p_ename cmd.Public Sub Delete_Rec() If con.Int).Parameters.StoredProcedure cmd.SelectCommand.Int).ExecuteNonQuery() cmd.Closed Then con.State = ConnectionState.Fill(ds) Return ds End Function Public Sub Save_Rec() Implements intcom.VarChar.Open() End If Dim cmd As New SqlCommand("delemp".

StoredProcedure cmd.CommandType = CommandType. 50).Add("@ed". SqlDbType.Parameters.Add("@en".104 - .Parameters. SqlDbType.Open() End If Dim cmd As New SqlCommand("updemp".Int).ExecuteNonQuery() cmd.Add("@eno".VarChar.VarChar. SqlDbType.Parameters. Value = p_ename cmd. 50).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 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 It’s me . SqlDbType.Int).Public Sub Update_Rec() If con.Add("@es".State = ConnectionState.Parameters.Value = p_esal cmd.Value = p_empno cmd. Value = p_eadd cmd.Closed Then con.Dispose() con. con) cmd.

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.Text) obj. "DataBase=dbemployee.Page Dim obj As New nsemp.p_empno = Convert.Save_Rec() TextBox1.aspx.cs Imports System.UI. ByVal datavalue As String) Dim adp As New SqlDataAdapter(qry. ByVal datatext As String.Load End Sub Protected Sub Button1_Click() obj.Text = "" It’s me .DataValueField = datavalue obj.p_esal = TextBox4. ByVal obj As ListControl.Text = "" TextBox2.uid=sa") Dim ds As New DataSet adp.Fill(ds) obj.p_eadd = TextBox3.Web.DataTextField = datatext obj.DataSource = ds obj.clsemp Protected Sub Page_Load() Handles Me.DataBind() End Sub End Class End Namespace In Default.ToInt32(TextBox1.Text obj.Text obj.Data Partial Class _Default Inherits System.105 - .p_ename = TextBox2.Text obj.Text = "" TextBox3.

p_esal = TextBox4.p_empno = Convert.Find_rec() Dim r As DataRowView r = ds.Text = "" TextBox4.ToString() TextBox4.Text obj.Text obj.106 - .p_ename = TextBox2.Text = "" TextBox2.Text = "" TextBox2.Click obj.Fill_Data("select * from tbemp".Text = r(2).DefaultView(0) TextBox1.Text = "" End Sub Protected Sub Button3_Click() Handles Button3.Click obj.Delete_Rec() TextBox1.ToInt32(TextBox1.Click nsemp.Text = r(0).comfunction. "ename".ToInt32(ListBox1.Text) obj.ToString() End Sub End Class It’s me .TextBox4.Text = "" End Sub Protected Sub Button4_Click() Handles Button4.SelectedIndex) Dim ds As New DataSet() ds = obj.p_empno = Convert.Text = "" TextBox3. ListBox1.Text = r(4).Text = "" End Sub Protected Sub Button2_Click() Handles Button2.ToInt32(TextBox1.p_empno = Convert.ToString() TextBox2.Text) obj.Tables(0).Update_Rec() TextBox1.p_eadd = TextBox3.Text = "" TextBox4.Text = "" TextBox3.Text = r(1). "empno") End Sub Protected Sub ListBox1_SelectedIndexChanged() obj.Text obj.ToString() TextBox3.

set. } String p_eadd { get. } } public abstract class clscon { protected SqlConnection con = new SqlConnection(). void Delete_Rec().107 - .Net) • • Add Webconfig file and a class file Place 4 textboxs . It’s me . set. set. public clscon() { con. } public interface intemp { Int32 p_empno { get. } String p_ename { get. 4 button and a listbox  AutoPostBack true using System.SqlClient.DATABASE HANDLING WITH CLASS (C#.Data. namespace nsemp { public interface intcom { void Save_Rec(). void Update_Rec(). DataSet Find_rec(). } Int32 p_sal { get. set.ConnectionString = ConfigurationManager.

} } public string p_ename { get { return en. es. intcom.108 - . #region intemp Members public int p_empno { get { return eno. } It’s me . } set { es = value. } } public class clsemp : clscon. } } public int p_sal { get { return es.ConnectionStrings["cs"]. private String en. ed.ConnectionString. intemp { //we define interface after comma and to impliment them right click on it n click implement interface private Int32 eno. } set { eno = value. } set { en = value.

Add("@ed".Add("@eno". SqlDbType.Closed) { con. cmd. cmd.Open(). SqlDbType. con).Value = p_ename. cmd. cmd.Add("@en". con. cmd.Value = p_sal.Parameters. } } #endregion #region intcom Members public void Save_Rec() { if (con.ExecuteNonQuery().Value = p_empno.Open().Int).Dispose().State == ConnectionState.StoredProcedure. cmd. con).Parameters. SqlDbType. 50).VarChar.Int).Value = p_eadd. cmd. SqlDbType. 50). } SqlCommand cmd = new SqlCommand("updemp".109 - . } SqlCommand cmd = new SqlCommand("insemp". } public void Update_Rec() { if (con.} public string p_eadd { get { return ed.State == ConnectionState.VarChar. It’s me .CommandType = CommandType.Parameters. } set { ed = value.Parameters.Closed) { con.Add("@es".Close().

} public void Delete_Rec() { if (con. cmd. SqlDbType.String datatext.ListControl obj. con.Open(). DataSet ds = new DataSet(). cmd.Value = p_eadd. } public DataSet Find_rec() { SqlDataAdapter adp = new SqlDataAdapter("findemp".Int). } SqlCommand cmd = new SqlCommand("delemp".Add("@es".Parameters.Close().Value = p_empno.Add("@eno".CommandType = CommandType. adp.StoredProcedure.Parameters. cmd.VarChar. SqlDbType. cmd. con).110 - .VarChar.CommandType = CommandType.Add("@ed".Parameters. } #endregion } public class clscomfunction { public static void fill_data(String qry.ExecuteNonQuery().ExecuteNonQuery(). 50). SqlDbType.Dispose().Close().Add("@eno".StoredProcedure. SqlDbType.SelectCommand. SqlDbType. cmd.Value = p_empno.Add("@eno". cmd. adp. 50).Fill(ds). con.Parameters. return ds.Closed) { con. cmd.State == ConnectionState.Add("@en".SelectCommand.Value = p_empno.StoredProcedure.Int). adp.Int).Int).Dispose(). cmd.Parameters. String datavalue) It’s me . SqlDbType. cmd. cmd. con).cmd.CommandType = CommandType.Value = p_sal.Parameters.Value = p_ename.

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 = ""; } 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; It’s me - 111 -

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

- 112 -

• 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; } } 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 { It’s me - 113 -

} set { es = value. } set { en = value. } set { ed = value. } set { eno = value.114 - . } } #endregion } It’s me . } } public string p_ename { get { return en. } } public string p_eadd { get { return ed. } } public int p_esal { get { return es.return eno.

SqlDbType.Add("@en". SqlDbType. SqlDbType.p_ename. cmd. 50).Value = p. con).Parameters. public clscon() { con.public abstract class clscon { protected SqlConnection con = new SqlConnection().Value = p. cmd.p_esal.Add("@ed".p_empno.Value = p.Parameters. cmd. SqlDbType.Add("@eno".Value = p.ConnectionString. 50).p_eadd.Parameters.CommandType = CommandType.Parameters.p_eadd. con. cmd.VarChar.VarChar. cmd. SqlDbType.Add("@eno".Open().StoredProcedure. cmd. cmd. con).StoredProcedure.CommandType = CommandType.Value = p.115 - .Add("@es". } public void update_rec(clsempprp p) { if (con.Value = p. SqlDbType.Parameters.Close().State == ConnectionState.Int).ExecuteNonQuery().Parameters. cmd.VarChar.State == ConnectionState.Dispose().Int). cmd.Open().Closed) { con. It’s me .Closed) { con. cmd. SqlDbType.Add("@ed".Int).p_empno. 50).Parameters.p_ename. ConnectionStrings["cs"]. } } public class clsemp : clscon { public void save_rec(clsempprp p) { if (con. } SqlCommand cmd = new SqlCommand("insemp". cmd.Value = p.Add("@en". 50).ConnectionString = ConfigurationManager.VarChar. } SqlCommand cmd = new SqlCommand("updemp".

CommandType = CommandType.ToInt32(dr[3]). con.Open(). dr = cmd.Dispose(). while (dr.p_ename = dr[1].StoredProcedure.Add("@eno".Close().Parameters.CommandType = CommandType.Add("@es".State == ConnectionState. obj. return obj.p_esal.Close(). } public void delete_rec(clsempprp p) { if (con. cmd. SqlDbType.ExecuteNonQuery().Int). cmd.con). cmd. con). } public List<clsempprp> find_rec(Int32 eno) It’s me . k.Parameters.Dispose(). List<clsempprp> obj = new List<clsempprp>().ToString().Int).p_empno = Convert. cmd.p_empno.Read()) { clsempprp k = new clsempprp().StoredProcedure.p_esal = Convert.cmd. con.ToInt32(dr[0]). k.Open(). SqlDbType.Close().116 - .Dispose().Close().State == ConnectionState. } SqlCommand cmd = new SqlCommand("dispemp". } public List<clsempprp> Dis_rec() { // List is a class which is used to create custom collection if (con.Value = p.Closed) { con.Closed) { con.Value = p. cmd. k.ExecuteReader().Add(k).ToString(). } SqlCommand cmd = new SqlCommand("delemp". k. con. } dr.p_eadd = dr[2]. cmd. SqlDataReader dr.ExecuteNonQuery(). cmd. cmd.

k.Dispose().p_ename = dr[1]. dr = cmd. } } } • Place formview DataKeyNames  p_empno Choose Data source  object data source1 Enable Paging  true Place object data source1 • Used with 3 tier architecture • Stateless ( after doing 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 • • It’s me .StoredProcedure.Add(k).ToString().ToInt32(dr[0]).Close().Open(). if(dr. } SqlCommand cmd = new SqlCommand("findemp".p_eadd = dr[2].CommandType = CommandType.ExecuteReader().con).SqlDbType. SqlDataReader dr. return obj. obj. } dr.Value =eno.Add("@eno". k. k.Int).{ if (con.117 - .ToInt32(dr[3]). cmd.State ==ConnectionState. clsempprp k = new clsempprp(). List<clsempprp> obj = new List<clsempprp>(). cmd.Parameters.p_esal = Convert.Closed) { con.ToString().Read(). con. cmd.Close().HasRows) { dr. k.p_empno = Convert.

118 - .• • • • Place List box • Choose Data source  object data source2 • DataField ename • DataValueempno Place object data source1 configure data source of object data source1 • Select clsemp • Select  choose method  Disp_Rec Place another formview DataKeyNames  p_empno Choose Data source  object data source Enable Paging  true Place object data sourceconfigure 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 .

} String p_ename { get.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 .Collections. self described.Data. Just copy & run it. using System. set. // To create custom collection (array of objects) namespace nsemp { public interface intemp { Int32 p_empno { get.119 - . set. (no need to register the DLL. 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.SqlClient. } String p_eadd { get. It’s me .Generic. } Int32 p_esal { get.

ed. es. } } public class clsempprp:intemp //right click to implement interface { private Int32 eno. } } public string p_ename { get { return en. private String en.120 - . } set { en = value. } set { es = value.set. } } public string p_eadd { It’s me . } } public int p_esal { get { return es. } set { eno = value. #region intemp Members public int p_empno { get { return eno.

ExecuteNonQuery().CommandType = CommandType.Parameters.VarChar.Closed) { con.Parameters. } } #endregion } public abstract class clscon { protected SqlConnection con = new SqlConnection(). cmd.p_esal.State == ConnectionState.Add("@ed". con. cmd. SqlDbType. con).Dispose(). cmd.Add("@es".p_eadd. cmd. 50). } set { ed = value. SqlDbType. cmd. } public void update_rec(clsempprp p) It’s me .p_empno.Value = p.Int).Value = p.StoredProcedure. cmd.ConnectionString = ConfigurationManager. public clscon() { con.VarChar.Open(). cmd. SqlDbType.121 - .Int).Close().Value = p.p_ename.Parameters. } SqlCommand cmd = new SqlCommand("insemp". 50).get { return ed.Add("@en". SqlDbType. ConnectionStrings["cs"].Add("@eno".Parameters. } } public class clsemp : clscon { public void save_rec(clsempprp p) { if (con.ConnectionString.Value = p.

SqlDbType. cmd. 50).StoredProcedure.Value = p. con.VarChar.Add("@en".Parameters. cmd. } SqlCommand cmd = new SqlCommand("updemp". SqlDbType. cmd. dr = cmd. cmd.Value = p.CommandType = CommandType. cmd. cmd. SqlDbType.Closed) { con.p_esal.p_empno.Int). SqlDbType.{ if (con. con).ExecuteNonQuery(). SqlDbType. } SqlCommand cmd = new SqlCommand("dispemp".ExecuteNonQuery().Read()) { It’s me .Value = p. 50).VarChar.Close().Open(). cmd.StoredProcedure.Value = p.Add("@es".Dispose(). } public List<clsempprp> Dis_rec() { // List is a class which is used to create custom collection if (con.Open().Value = p.Closed) { con. cmd.State == ConnectionState. cmd.Open().Parameters. while (dr.Int).p_ename. } SqlCommand cmd = new SqlCommand("delemp".Dispose().Parameters.ExecuteReader().StoredProcedure. cmd.CommandType = CommandType. SqlDataReader dr. List<clsempprp> obj = new List<clsempprp>().State == ConnectionState.Add("@eno".Add("@eno". con).Closed) { con. } public void delete_rec(clsempprp p) { if (con.CommandType = CommandType.Parameters.State == ConnectionState.Close().p_empno. cmd.122 - .Int). cmd.con).Parameters.p_eadd.Add("@ed". con.

k. k. List<clsempprp> obj = new List<clsempprp>().p_eadd = dr[2]. cmd.Add(k).CommandType = CommandType. SqlDataReader dr.p_empno = Convert. dr = cmd.ToString(). return obj. k.clsempprp k = new clsempprp().ToString().Add("@eno".ToString().p_ename = dr[1]. obj.Close().SqlDbType. cmd.Close().123 - . cmd.Value =eno. } dr.p_eadd = dr[2].Int).ToInt32(dr[3]).ToInt32(dr[3]). k.ToString(). cmd.p_empno = Convert. con.Close().ToInt32(dr[0]). if(dr. return obj.Close(). con.Dispose().Open(). obj.Read(). } public List<clsempprp> find_rec(Int32 eno) { if (con.Dispose().HasRows) { dr. } } } • • Built  built class library If DLL is in C# or Vb & front in opposite language then that is called COM interportability It’s me . k. } SqlCommand cmd = new SqlCommand("findemp".p_esal = Convert.Parameters.p_ename = dr[1]. k. } dr. clsempprp k = new clsempprp(). k.p_esal = Convert.ToInt32(dr[0]).State ==ConnectionState.Closed) { con.Add(k).con). k.StoredProcedure.ExecuteReader().

Text = "". TextBox1.Focus().Text = "".Text = "".EventArgs e) { objprp.Generic. EventArgs e) { } protected void Button1_Click(object sender. TextBox2.p_eadd = TextBox1. enable post back  true using System.p_esal = Convert. TextBox1.p_empno = Convert.Web.ToInt32(TextBox1. protected void Page_Load(object sender.Text = "". TextBox3. obj.124 - .EventArgs e) { objprp.ToInt32(TextBox4.delete_rec(objprp). obj.clsemp(). TextBox1.Text = "". TextBox3.save_rec(objprp).Collections.clsempprp(). nsemp.DataBind().p_ename = TextBox2. TextBox4.ToInt32(TextBox1.Text = "".Text = "".Text.• • Path classlibrary1/classlibrary1/Bin/Debug To add a DLL file website add reference  browse DATABASE HANDLING USING DLL FILE • • • • Place 4 textbox.Text). ListBox1.Focus().Text). objprp. one listbox Add DLL file Place Object data source  configure  clsemp  select  disp_rec() Bind it with listbox. 4 buttons .DataBind(). } protected void Button2_Click(object sender.clsemp obj = new nsemp. TextBox1. objprp. public partial class _Default : System.Page { nsemp. objprp.UI. TextBox2.Text = "".p_empno = Convert. ListBox1. TextBox4. It’s me .Text.clsempprp objprp = new nsemp.Text).

clsempprp> k. } protected void Button4_Click(object sender.update_rec(objprp).p_ename = TextBox2. TextBox1.p_esal. TextBox1.Text = "".find_rec(Convert.Text.ToInt32(TextBox1.p_empno.Text = "". ListBox1. } protected void ListBox1_SelectedIndexChanged(object. TextBox3.125 - .EventArgs e) { TextBox1. TextBox4. k[0].Text = "".ToString().ToInt32(ListBox1.} protected void Button3_Click(object sender. obj.Text = "".Text = "". TextBox2.p_ename.Text = "".ToInt32(TextBox4. k = obj.p_eadd.Text = "".Text TextBox2.EventArgs e) { objprp.Focus().p_eadd = TextBox1.Text } } = = = = k[0]. TextBox3. e) { List<nsemp.Text). TextBox4. objprp. TextBox2. TextBox1.p_empno = Convert. k[0]. It’s me .Text TextBox3.DataBind().ToString().Text). k[0].Focus().p_esal = Convert.SelectedIndex)). objprp.Text = "".Text TextBox4. objprp.Text. TextBox1.

master Ek page par ek se jada master page ho sakte hai Layout  Insert table  Template  header. In" encoding="utf-8" ?> <Advertisements xmlns="http://schemas.aspx</NavigateUrl> <AlternateText xmlns="">First Add</AlternateText> <Keyword xmlns="">Top</Keyword> <Impressions xmlns="">1</Impressions> // impressions is used to tell the ration of add to display </Ad> <Ad xmlns=""> <ImageUrl xmlns="">a2.gif</ImageUrl> <NavigateUrl xmlns="">default2. content page(HTML) and they combine at run time to make one -Schedule-File"> <Ad xmlns=""> <ImageUrl xmlns="">a1.gif</ImageUrl> <NavigateUrl xmlns="">default3.MASTER PAGES • • • • • • • • • • • • • For common layout on all the pages. To insert master page website Add new item  Master page Extension of master page is *.126 - . In 1.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.aspx</NavigateUrl> <AlternateText xmlns="">Second Add</AlternateText> <Keyword xmlns="">Top</Keyword> It’s me .1 there was no master pages concept we use web user control but in this at every page code copy hota hai.0 there is two pages Master Page(design).

public partial class MasterPage : System.Page { protected void Page_Load(object sender.MasterPage { public Color p_fcolor { get { return Label1.master"%> Master Page using System.FindControl("label1")).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.Text = "Page2". } } • To excess properties made master page.127 - .Drawing.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.UI. EventArgs e) { Label lb = (Label)(Master.gif</ImageUrl> <NavigateUrl xmlns="">default5.gif</ImageUrl> <NavigateUrl xmlns="">default4. } It’s me .<Impressions xmlns="">2</Impressions> </Ad> <Ad xmlns=""> <ImageUrl xmlns="">a3. in Content page • First Made content page strong type by adding following line in source <%@ MasterType VirtualPath ="~/MasterPage.ForeColor.UI.Web. lb.Web.

0" > <siteMapNode url="" title="Menu" description="Menu"> <siteMapNode url="default2.Red. protected void Page_Load(object sender.aspx" title="Page4"></siteMapNode> </siteMapNode> </siteMapNode> </siteMap> • SiteMapPath  properties Path separator  >>> It’s me .0" encoding="utf-8" ?> <siteMap xmlns="http://schemas. } • • • 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.128 - .com/AspNet/SiteMapFile-1. } } } Content Page using System.aspx" title="Page1" description="Page1" /> <siteMapNode url="default3.p_fcolor = Color. No need to bind it if there is only one SiteMap file SiteMap File • Add it from WebsiteAdd new items  SiteMap <?xml version="1.ForeColor = value.aspx" title="Page2" description="Page2" /> <siteMapNode url="" title="Sub Menu" description="Sub menu"> <siteMapNode url="default4.set {" title="page3"></siteMapNode> <siteMapNode url="default5. EventArgs e) { Master.Drawing.

129 - .• • 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.Web. in SiteM apDataSource  properties Site MapProvider  xz It’s me .sitemap"/> <add name="xz" type="System.XmlSiteMapProvider" siteMapFile="Web.XmlSiteMapProvider" siteMapFile="Web2.web> <siteMap enabled="true" defaultProvider="xy"> <providers> <add name="xy" type="System.Web.sitemap"/> </providers> </siteMap> • To bind navigator tool with second SiteMap.config write <system.

130 - . } It’s me .TO UPLOAD FILE ON SERVER • • From toolbox  FileUpload Place a button (upload) protected void Button1_Click(object sender. EventArgs e) { String st = FileUpload1. // uploads path fp = fp + "\\" + st.PostedFile. FileUpload1.Substring(i + 1).LastIndexOf("\\"). // file path at client machine Int32 i = st. // "\" used with excape sequences that's y we use "\\" st = st.FileName.SaveAs(fp).PostedFile. // st = file name only //create a upload folder on server to store uploades files String fp = Server.MapPath("uploads").

UI.FileName.Open.IO.Close(). // lastIndexOf starts Searching from right hand side SqlConnection con = new SqlConnection(). fn = FileUpload1.SqlClient.Read). ConnectionStrings["cs"].Page { protected void Button1_Click(object sender. using System.Data.EventArgs e) { Int32 ln.ConnectionString. String ext. 0.ConnectionString = ConfigurationManager.Substring(fn.FileName. // FileStream is used to read/write data in binary format fs. FileAccess. public partial class _Default : System.ContentLength.PostedFile.PostedFile. Byte[] ar = new byte[ln]. ext = fn. String fn.Read(ar.Open().PostedFile.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.")).1). con.131 - . FileMode. It’s me .Web. ln = FileUpload1.LastIndexOf(". FileStream fs = new FileStream(FileUpload1. con. fs. ln .

50).Add("@name".Connection = con.ExecuteNonQuery().ConnectionString = ConfigurationManager. cmd. SqlDbType.ToInt32(TextBox1.ConnectionString. cmd. dr[2]  extension String fn.Add("@id". cmd. @ext)". a = Guid.Text).ExecuteReader(). SqlDbType.Read().132 - .ToInt32(TextBox2.Add("@ext".Parameters. SqlDataReader dr. EventArgs e) { SqlConnection con = new SqlConnection(). cmd.Open(). cmd. Byte[] ar = (Byte[])(dr[1]). // in dr[0]  id.CommandText = "select * from tbimage where imageId=@id".NewGuid(). It’s me . con. SqlDbType. cmd.CommandText = "insert into tbimage values(@id. } To retrieve it • • Place textbox for id Place Image tool and a button protected void Button2_Click(object sender. dr[1]  image in binary.Value = ar.Value = Convert.Value = Convert.ToString(). con. cmd. SqlCommand cmd = new SqlCommand(). dr = cmd. cmd. ConnectionStrings["cs"].Text).Dispose(). con.Parameters.HasRows) { dr.Close(). @name.Value = ext.Int). if (dr. SqlDbType.SqlCommand cmd = new SqlCommand().VarChar.Connection = con.Parameters.Image). cmd.Add("@id".Int). String a. cmd.Parameters.

} dr.gif”).MapPath(".ImageUrl = fn. FileMode. } To remove files protected void Button3_Click(object sender.FullName). fs. foreach(FileInfo f in fi) { fi. fs. FileAccess. 0.MapPath(a + dr[2]. //". fn = Server. Image1.Write).Dispose(). } } It’s me . con.Length .Create. ar.")).Delete(f.Close().133 - .ToString()).GetFiles("*. cmd.//Guid  Global unique identifier. EventArgs e) { DirectoryInfo dir = new DirectoryInfo(Server.Close(). FileStream fs = new FileStream(fn." --> Current folder otherwise folder name FileInfo fi = dir.1).Write(ar.Close().

we can add them in Database.Columns[0].Columns. item.Columns. c.Add(c). //Datatable used to create temporary table DataColumn c = new DataColumn("icode".Columns. c. It is just like 2D array.Int32")). Type. But formatted like tables in db We can make primary key.Add(c). update. c.GetType("System. Type.Expression = "iqty * irate". Type. item. delete query They are on client side only.AutoIncrement = true.GetType("System. c = new DataColumn("irate".Int32")).Columns.Columns.Int32")). item. item. c = new DataColumn("iamt". pk[0] = item.GetType("System. It’s me . c.AllowDBNull = false.GetType("System. c = new DataColumn("iqty". EventArgs e) { DataTable item = new DataTable("tbitem"). DataColumn[] pk = new DataColumn[1]. item.Int32")).TEMPORARY TABLES • • • • • • No insert. expression columns Place a GridView protected void Page_Load(object sender. select. c = new DataColumn("iname". c.GetType("System. foreign key.Add(c).AutoIncrementSeed = 101. Type.Add(c).String")). Type.Add(c).134 - . If conform.AutoIncrementStep = 1.

item. r[1] = "Pen".Rows.Text = item.Add(r). EventArgs e) { DataTable dep = new DataTable("tbdep"). item.NewRow(). r[2] = 70000.Add(new DataColumn("dname". GridView1. r[3] = 4. GridView1.Add(r). It’s me .GetType("System.Int32"))). r[3] = 7. r[3] = 1. r[1] = "Laptop".Columns.Columns. //to add data in table DataRow r. r[1] = "Scale". null). r[2] = 10. item. r = item.Add(r).NewRow(). r[2] = 25000. r[2] = 5.NewRow().String"))). Type. r[3] = 2.Rows. r[1] = "computer".item.Rows. r = item.PrimaryKey = pk.Rows. dep. // null is for filter or we can write condition like "iamt>500" } Relation of Tables protected void Page_Load(object sender. item. r = item.DataSource = item.DataBind().Add(r). DataRow r. TextBox1.Compute("Sum(iamt)".ToString().Add(new DataColumn("dno". r = item. dep.NewRow(). Type.GetType("System.135 - .

Type. r[1] = "Civil".Add(emp).Columns.NewRow().Int32"))).Add(new DataColumn("eadd". r = dep.Columns[4].Columns.String"))).GetType("System.136 - . DataRelation rel = new DataRelation("myrelation".GetType("System.String"))).//Parent DataSet ds = new DataSet().Rows. r = dep. emp. Type. ds. r[0] = 3. r[1] = "Information Technology". emp.Int32"))). emp.Columns.Rows.Add(dep). dep.NewRow(). //Foreign key DataColumn c1 = emp. r = dep. dep.Tables. c2. r[1] = "Electrical".Add(r).Tables. emp.NewRow(). dep.r = dep. Type.Add(r).Add(new DataColumn("ename".Columns.GetType("System. DataTable emp = new DataTable("tbemp"). Type.ParentRelations. r[0] = 1. ds. r[0] = 4.GetType("System. ds.Add(new DataColumn("esal".Rows.NewRow().Add(new DataColumn("edno". Type.//Child DataColumn c2 = dep.Add(r). dep. //Always child make a relation with parent not vice versa It’s me .Add(new DataColumn("empno".Add(rel). emp. r[1] = "Electronics". r[0] = 2.Add(r).Tables[0]. c1).Int32"))).Rows.Columns.GetType("System.Columns[0].

Rows.r = emp. emp.NewRow().137 - . r[2] = "Ambala". r[1] = "Amit". r[4] = 1. r[0] = 1. // Enter edno dno which is available in dep table only otherwise error } It’s me . r[2] = "Ambala". emp. r[3] = 20000. r = emp.NewRow().Add(r).Rows. r[3] = 20000. r[0] = 1. r[1] = "Amit". r[4] = 2.Add(r).

.Net Coz DLL is Specific to CLR.ASSEMBLIES • • • • • • • DLL is known as Assembly in .. • • • • To create Share file • • • • Start  All Programs  Ms Visual Studio 2005  Visual Studio tools  Visual Studio Command Prompt Cd\ Cd ClassLibrary1 Cd ClassLibrary1 It’s me . Assemblies are logic units. English) If DLL Project me add ho jaye toh woh Private hai otherwise Shared hai. Satellite Assemblies is used to create site in multiple languages(Hindi. 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\.138 - .

txt In TextFile In new website add new text file Website  add new items  text file • File name  German -----. • User using older version will get only old methods but new user get all methods To create Satellite Assembly • To check the language of browser Internet Explorer  tools  Internet options  languages Codes English -----.en-us French ------. en is culture.en-us.txt • Add one more text file File name  abc.snk”)] and compile it • In Command prompt write > GacUtil -I ClassLibrary1 Copy to GAC GAC utility (to add version in GAC) • Now Add DLL in project Website  Add reference  browse  classLibrary1  obj debug DLL file • 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• • • Cd obj Cd Debug Sn –k abc.139 - • • .txt A = Welcome B = English C = Language D = US It’s me .cs • In last write [Assembly: AssemblyKeyFile(“ us is region • Add one more text file File name  abc.cs  solution explorer  properties  AssemblyInfo.en-us.snk To write in output file Strong Name command • In ClassLibrary class1.txt //Where abc is base name.

fr-be.Net C:\website\resgen abc.140 - .Globalization" %> <script runat="server"> void Application_Start(object sender.resources C:\website\resgen abc.en-us.• • In TextFile abc.txt abc.resources In a resource file o we can store  Bit map  Icons  Common messages o They are compiled o Compressed data In page place DropDownList o Edit Items  Text  English Value  en-us  Text  French Value fr-be  Text  German Value  de-at Add Global Application class o EventArgs e) { // Code that runs on application startup It’s me .txt A = hbbkjbckd B = German C = gycdakcb D = chdihcdn To convert text file into resource file goto command prompt of .txt" %> <%@ Import Namespace="System.txt A = hbjgj B = French C = gchghgcv D = hvjvjhy In TextFile abc.asax o Ek project me ek hi ho sati hai o To manage application ans session events • • • • <%@ Import Namespace=" C:\website\resgen abc.Resources" %> <%@ Import Namespace="System.txt abc.

protected void Page_Load(object sender. It’s me . used by all files) // yeh wohi resources file uthaiga jiska base name "abc" hoga } // select BeginRequest event of Application protected void Application_BeginRequest(object.CurrentCulture.CurrentCulture = new CultureInfo("en-us").CurrentThread.UI.MapPath(".CurrentCulture=new CultureInfo (Request.// yeh cod ek hi baar fire hota hai Application["ab"] = ResourceManager. null).CurrentThread. } Thread. } catch { Thread. CreateFileBasedResourceManager ("abc". // in this there is culture specfic classes public partial class _Default : System.CurrentThread. EventArgs e) { rm = (ResourceManager)(Application["ab"]).CurrentThread.Globalization. // application varible(Global. Server.CurrentUICulture = Thread. // we use threads coz we dont want to change the language of browser but the language of current instance of browser using System.Page { ResourceManager rm.ToString()).UserLanguages[0]. EventArgs) { // jitni baar page server par jata hai yeh event fire hota hai try { Thread. } Coding using System.Web.").Resources. using System.141 - .Threading.

Label4.142 - .if (Page.CurrentUICulture = new CultureInfo(d). } } private void SetCul(String d) { Thread.CurrentThread.Text = rm.GetString("B"). // change language of current thread Label1.Text = rm. Label2.Text = rm.Text = rm.GetString("D").GetString("A").GetString("C"). } protected void DropDownList1_SelectedIndexChanged() { SetCul(DropDownList1.SelectedValue).Text = rm.Text = rm.GetString("D"). Label3.GetString("A"). Label4.Text = rm.Text = rm.GetString("C").IsPostBack == false) { Label1. Label3. } } It’s me . Label2.GetString("B").

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. • It is faster than server side. 4 technology included in client side state management o Cookies o View state o Query string o Hidden fields o Control state (in Asp.0 only) 4 technology included in server side state management o Sessions o Application o Profile (in Asp. • Slow. 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.Net 2.State Management • • • • Common in all web development language like PHP. .143 - • • • . java. State management techniques have been introduced to store page information in server around trip. 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 only) o Cache To check there performance we check three things according to our requirement o Storing capacity o Type of information It’s me .Net 2.

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 Scope • Though out the website.o 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.144 - . o Cookies store • Impersistence cookies in browser memory • Persistence cookies in cookies folder (Document & settingusernamecookies) o It can store 4096 bytes (4kb) of data internet explorer but dependent on browser or on version. on all the pages of website. • So it is not reliable which means we are not sure that it will run on client machine or not. o A web site can create maximum 20 cookies o Cookies expiry date/time is of server not of client.(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 A cookie can store information in form of key value pairs. 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 . • Size limitation • User can manipulate • Some browsers don’t support cookies. o Disadvantage • Clients can disable on his/her cookies files. o Initial size of a cookie is 50 bytes (In which expiry date/time is store) o We can restrict cookies according to path o Cookies are URL specific which means yahoo wali gmail per use nahi hogi.

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 only) o Every webpage contain a hidden field name as “_ _viewstate” which is provided by Microsoft.• • • There is no expiry date/time. o It is easy to use just set EnableViewState property either to True or False o We can specify encryption mode. page size in version 2. o Disadvantage • Information can be seen by user so not so secure • Internet URL limit (2096 characters) o Scope • Upto next page. number as well as object.145 - . o Disadvantage • Large volume of data ke case me performance is slow o Scope • Current page only. compressed form and encoded. 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 .  Hidden Field o Advance of hidden fields is view state o In this we can only store text not object o Scope • Only on current page  Control State It’s me .  Query String o It is used to transfer text as well as numeric information between continues page requests. o “_ _ViewState store information as multiple key pairs (as array) o It stores information in hasted (it helps in data retrieving faster).(string value only) o The information is concentrated with URL.0 o Page size by default is -1(unlimited) we can specify bytes.

we can change it.Net State Service.Avendon forcefully expires the session. o Session expiry time by default is 20 min. o SessionId’s length is 128 bits.146 - . o Session.o In this custom control (made by programmer) ki state management hoti hai Server Side State Management  Application o When first user site kholta hai Application Start event fire hota hai o Application Start event ek hi baar fire hota hai. o Hit counter( to view visitors) is example of this state management  Session o Server generates 2 copies of unique sessionId. o Application End event tab fire hota hai jab last visitor site band karta hai. o Application variable can be string as well as objects o Scope -.Thought-out the application o Application variable sabhi user ke liye same hota hai. o One copy on client side(in session cookie) other on server side(memory) o In . It’s me . o If we open a new window then we get the same sessionId o 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. Jab yeh fire hota hai iske baad Application Start event fire hota hai. o When another user site kholta hai HTTP Application class ka instance banta hai. including when browser is closed. • Modes o State server  To store session on different server  Note: To implement this we must start ASP.Net we can create cookie less application then there is QueryString in URL. yeh event bhi ek hi bar fire hota hai.

o Two types of users  Authenticated (inka profile ASP.45. themes .   Profile o To set colors. Response.Net State Service Session destroy ho jate hai. // 3hr 45min 35sec Response. o Out process ke case me session end event file nahi hota.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. // subkey ck.Text == "xyz") { HttpCookie ck = new HttpCookie("myckk"). TextBox1. } } • Add new page and place two textboxes. // 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.Cookies.Add(new TimeSpan(3. EventArgs e) It’s me .Values.Expires = DateTime.Text).147 - . EventArgs e) { if (TextBox1.Now.35)).Expires=DateTime.aspx").If we reset ASP. a label and a button protected void Button1_Click(object sender.Text == "abc" && TextBox2.Add(ck).Now.Text).Add("uname".Values. ck.Redirect("default2. o SQL Server  We store session in SQL database  Two type of system define database • Temp Db o If we reset SQL server service then Temp Db ka data delete ho jata hai • Asp State o Ye data permanent hai. back ground etc different for different users. TextBox2.Add("upass".AddMinutes(30). // subkey ck.

It’s me .AddHours(2).Now.Text = "cookies not created".Text = "welcome".Values["uname"]. Response.Text="check username & password". kkk.Value = "abc".Cookies. "abc").Expires = DateTime.AddHours(2). Response. ///////////////////////////////////////////////////////////// HttpCookie kk = new HttpCookie("un".Expires = DateTime.Value["up"] = "xyz". } } } ///////////////////////////////////////////////////////////// Response.Cookies["un"]. kkk.ToString() == TextBox2. k.Expires = DateTime.Cookies["ui"]["up"] = "xyz".Cookies["ui"]. } else { if (k.Values["upass"].Now. Response.Expires = DateTime.Now.Cookies["myckk"].Text && k. } else { Label1.Value["un"] = "abc". ///////////////////////////////////////////////////////////// //Cookies with sub keys ///////////////////////////////////////////////////////////// Response.Cookies["un"]. if (k == null) { Label1.148 - .{ HttpCookie k = Request. Response.AddHours(2).AddHours(2).ToString() == TextBox1. /////////////////////////////////////////////////////////// HttpCookie kkk = new HttpCookie("ui"). kkk.Cookies["ui"]["un"] = "abc".Text) { Label1.Now.Add(k).

Response.Values.Write(Request.Values.ToString()).Write(d. { Response.Add(kkk). nv = a. Response.Value["un"].Count.Count.Write(Request.149 - .Value["up"].Cookies("ui"). ////////////////////////////////////////////////////////// // To read Sub Key ////////////////////////////////////////////////////////// Response. j < nv. Response.Cookies.Cookies["un"]. if (a.Write(qq.Write(Request.AllKeys.Cookies["ui"]["up"].Cookies. // Sub keys ke name ka array Int32 j.Cookies[i].Value).Cookies["un"]. ToString()+"Value:"+nv[j]. /////////////////////////////////////////////////////////// HttpCookie d = Request.ToString()).Collections. for (i = 0.ToString). ///////////////////////////////////////////////////////// HttpCookie qq = Request. j++) . i < Request.Value). Response.Write(qq. for (j = 0.Specialized.ToString). /////////////////////////////////////////////////////// // To print all the Cookies and thire value /////////////////////////////////////////////////////// Int32 i.Cookies["ui"] ["un"].HasKeys) { System. // Array ban jayega values ka String[] ar = a.Response. i++) { HttpCookie a = Request. It’s me .Write("Sub Key Name:"+ar[j]. NameValueCollection nv. //////////////////////////////////////////////////////////// // To Read Value// /////////////////////////////////////////////////////////// Response.

// this cookie work with admn folder only QueryString • Place 2 textboxes and one button protected void Button1_Click(object sender.aspx?ab="+TextBox1.Text).ToString() + Request. } It’s me . EventArgs e) { Label1.Text = "Welcome:" + Request.ToString(). } } /////////////////////////////////////////////////////////// // To restrict for path ////////////////////////////////////////////////////////// kk.QueryString["ab1"].Path = "admin".Text + "&ab1="+TextBox2.Redirect("default2.ToString() + "<br>").aspx • Place a label and one button protected void Page_Load(object sender. EventArgs e) { Response.150 - . // use "?" phele variable ke sath aur "&" rest ke sath } Default2.QueryString["ab"].

cs protected void Page_Load(object sender.aspx?ab="+id.Add("OnClick".").aspx It’s me .open("default2.width=350"). EventArgs e) { Button1.151 - . "abc('form1. } Default2.aspx.textbox1').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. "height=350."name".Attributes. // To open sub Window } </script> </head> Default.

e.Clear(). Request.window. opener.InnerText = e.QueryString["aa"] == null) { HttpCookie ck = new HttpCookie("myckk".Url.TagName = "a". EventArgs e) { if (Request.Expires = DateTime.ToString().Cookies.DayRenderEventArgs) { //Fire for each day e.Day.ToString().DayNumberText.Add(ck).Url } else { Label1. Response.Controls.Redirect("default2.Text = Request. lk.Controls.Date.QueryString["ab"]. } } Default2. // Kisi bhi tag ka kaam karwa sakte hai lk.AddDays(2).Cell. // To fetch url of current page use Request. HtmlGenericControl lk = new HtmlGenericControl().aspx.Add(lk).close()".QueryString["aa"].Day. e.ToString()).{0}. lk.Now.• • Place a calender control Calender  DayRender event protected Calendar1_DayRender(object.Attributes["href"] = String. ck.Format("javascript:window.ToShortDateString()). Response.value='{1}'.document. "sachin").aspx?aa=" + Request.152 - .cs It’s me .Cell. } To check whether cookies are enable or disable at client side • Place a label protected void Page_Load(object .

ToString(). } Response.SqlClient. EventArgs e) { String d.Add(k).153 - . } else { ds = (DataSet)(ViewState["abc"]). button and a grid view using System. } ViewState • Place a label.Page { protected void Page_Load(object sender.Text = "Read Data from Database".Redirect(d + "?aa=" + d1). // To expire cookie forcefully Response. d1.Data.Web. if (ViewState["abc"] == null) { ds = GetData(). public partial class _Default : System. } else { d1 = "cookie created".UI.Cookies. Label1. ViewState["abc"] = ds. EventArgs e) { DataSet ds.protected void Page_Load(object . Label1. k.Cookies["myckk"].Text = "Read data from Viewstate".Now. It’s me .DataBind(). GridView1. d = Request.DataSource = ds. } GridView1. HttpCookie k = Request.QueryString["aa"].Expires = DateTime. if (k == null) { d1 = "cookie not created".AddDays(-1).

adp.Visible = false.Visible = false. DataSet ds = new DataSet(). EventArgs e) { String st.ToInt32(ViewState["ctr"]) + 1. st = "Panel" + ViewState["ctr"].uid=sa").IsPostBack == false) { ViewState["ctr"] = 1.Fill(ds).ToString(). } } Panel on same screen • Place 4 panel and place buttons on them Next and prev protected void Page_Load(object sender. Panel3. st = "Panel" + ViewState["ctr"]. return ds.Visible = false. "database=dbemp. EventArgs e) { if (Page.ToString(). Panel2. It’s me . p. Panel4.154 - .Visible = false.Visible = true. ViewState["ctr"] = Convert. Panel p = (Panel)(Page.} private DataSet GetData() { SqlDataAdapter adp = new SqlDataAdapter("select * from tbemp". } } public void Btn_Next(object sender.FindControl(st)). Panel1.

Visible = true.ToString().Visible = true.Lock(). Application. } public void Btn_Prev(object sender. Application["ctr"] = Convert. EventArgs e) { // Code that runs on application startup Application["ctr"] = 0.p = (Panel)(Page. p.EventArgs) { It’s me .FindControl(st)). p. st = "Panel" + ViewState["ctr"].FindControl(st)).155 - .cs protected void Page_Load(object .1. } • 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 when a new session is started Application.Visible = false. } void Session_Start(object sender. ViewState["ctr"] = Convert. Panel p = (Panel)(Page.FindControl(st)). EventArgs e) { String st. p = (Panel)(Page.ToInt32(ViewState["ctr"]) .aspx.UnLock().ToInt32(Application["ctr"]) + 1. } Default.ToString(). st = "Panel" + ViewState["ctr"]. p.

Redirect("default2.aspx • Place a gridview & a button protected void Page_Load(object .aspx"). If session mode is set to StateServer // or SQLServer. adp. Place a button using System.SqlClient.ToInt32(Application["ctr"]) . of user currently using this site void Session_End(object sender.Label1.Data. Application["ctr"] = Convert. EventArgs e) It’s me .config file. DataSet ds = new DataSet(). "database=dbemp.ToString(). protected void Button1_Click(object. Application. // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web. EventArgs e) { // Code that runs when a session ends.uid=sa"). the event is not raised.Lock().Text = Application["ctr"].156 - . } • To check the no. EventArgs e) { SqlDataAdapter adp = new SqlDataAdapter("select* from tbemp". 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. Response. Session["ss"] = ds. } Default2.1.Fill(ds).

aspx").Text = Session["ss"].Abandon().aspx. } } To reset Web server It’s me . // 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 . Response.DataBind().ToString(). EventArgs e) { if (Session["ss"] != null) { Label1.157 - . name  http://Localhost/aaa Place Button protected void Button1_Click(object . } protected void Button1_Click(object.Text = "No Data". } else { Label1. EventArgs e) { Session.DataSource = (DataSet)(Session["ss"]).cs • Place label protected void Page_Load(object.{ GridView1. } Default2. GridView1. EventArgs e) { Session["ss"] = "hello".Redirect("default2.

1:42424" timeout="20"></sessionState> • State server uses Asp.Net command mode • For TempDb Aspnet_regsql.0.web> <sessionState mode="StateServer" stateConnectionString="tcpip=127.exe –S sac –E –ssadd -sstype t • For ASPStateDb Aspnet_regsql.158 - .web> <sessionState mode="SQLServer" sqlConnectionString="server=cs.exe –S sac –E –ssadd -sstype p Where: • • -S  server sac  server name It’s me .iisreset (data in inproc will lost) Out Process State Service • Add web config file < State Service • To start it Control Panel Administrator Tool  Services  Asp.0.• • Goto visual studio command prompt Type --.uid=sa"> </sessionState> • • It uses two databases • TempDb • ASPStateDb To tell database • In .NetStateService Right Click  start • If we reset this service we will lost the session SQL Server • In Web Config write <system.

• • • -E  current user instance -U admin –P password (if user is sepecficed) • -ssadd  session state add database • -sstype  session state type • T  temporary • P  permanent In TempDb data is store in ASPStateTempSessions and if we reset SQLServerService data will lost In ASPStateDb data is permanent. Shopping Cart Default. 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.aspx?bid=" + It’s me .159 - .aspx • • • Place DataList. e) { Response.Redirect("Default2.gif" CommandName="Cart" runat="server" /> </ItemTemplate> • Set DatKeyField  bookId protected void DataList1_SelectedIndexChanged(object.

Redirect("default3.DataKeys[DataList1. e) { if (e.DataList1. ToString()).aspx?bid=" + DataList1.Item.CommandName == "Cart") { Response.SelectedIndex]. } protected void DataList1_ItemCommand(object source.DataKeys[e. 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> It’s me .ItemIndex].160 - .

FindControl("label1"))).DataSource = ds. } protected void DetailsView1_ItemCommand(object.Data. EventArgs e) { String st = "Select * from tbBook where bookId=" + Request.ConnectionStrings["cs"].Text). DetailsView1.SqlClient. adp.aspx?bid=" + ((Label)(DetailsView1. } } Default3.Fill(ds).DataBind().<asp:TemplateField HeaderText="Price"> <ItemTemplate> <asp:Label ID="Label5" runat="server" Text='<%# Eval("BookPrice") %>'> </asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /> </ItemTemplate> </asp:TemplateField> </Fields> using System.UI. DataSet ds = new DataSet(). EventArgs e) { Response.aspx • Place GridView It’s me . ConfigurationManager.Page { protected void Page_Load(object sender.Redirect("default3.ToString(). SqlDataAdapter adp=new SqlDataAdapter(st. public partial class Default2 : System. DetailsView1.161 - .Web. e) { } protected void Button1_Click(object .QueryString["bid"]. ConnectionString).

Type.GetType("System.String"))).Columns. tb.Columns.SqlClient.<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting" 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.Add(new DataColumn("ordAuthor". tb. tb.Data. tb.GetType("System. Type. Type.String"))).Add(new DataColumn("ordId".Web. Type. tb.Columns. public partial class Default3 : System.Page { protected void Page_Load(object sender.UI.String"))).Columns.Add(new DataColumn("ordPrice".Columns. It’s me .Add(new DataColumn("ordPub".Add(new DataColumn("ordTit".GetType("System. EventArgs e) { if (Session["ss1"] == null) { DataTable tb = new DataTable("Table"). Type.162 - . tb.Int32"))).Int32"))).GetType("System.GetType("System.Add(new DataColumn("ordQty".Columns.

r1[4]=Convert. DataRow r1 = ab.NewEditIndex. // for one row r = ds.Add(new DataColumn("ordAmt".Rows.Expression= "ordQty*ordPrice".EditIndex = e.DefaultView[0]. tb.GetType("System.DataBind(). ConfigurationManager. } } public void GrdBind() { GridView1.Tables[0]. Session["ss1"] = tb. DataRowView r.Fill(ds).ToString().Columns["ordAmt"]. SqlDataAdapter adp = new SqlDataAdapter(st. adp.ToInt32(r["BookPrice"]). ConnectionString).163 - . r1[1] = r["bookTitle"]. GrdBind().Int32"))). r1[5] = 1.ToInt32(((TextBox) (GridView1. GridView1. Type.Rows[e.ToInt32(r["bookId"]).Int32"))).GetType("System. DataTable ab = (DataTable)(Session["ss1"]). r1[2]=r["bookAuthor"].ToString(). } if (Page. r1[3] = r["BookPub"]. e) { GridView1.DataSource = (DataTable)(Session["ss1"]).Add(r1). } protected void GridView1_RowUpdating(object sender.RowIndex]. It’s me .DataBind(). r1[0] = Convert.Cells[5].Columns.IsPostBack == false) { String st. e) { DataTable tt = (DataTable)(Session["ss1"]).ConnectionStrings["cs"]. GridView1.RowIndex][5] = Convert. tb.DataSource = ab.Type. tt. DataSet ds = new DataSet().NewRow().ToString(). ab. GridView1. st = "select * from tbbook where bookid=" + Request.ToString(). } protected void GridView1_RowEditing(object sender.Rows[e.QueryString["bid"].

Authorization  means permission to user. Authentication Authentication of IIS 1. Digest AuthenticationThis authentication is by default provided by IIS and user password stored in encrypted form. 2. None We can also create user and password in webconfig and xml file.Controls[0])). Forms Authentication It is customized authentication and used mostly. } } SECURITY Security include 1. Authentication Types 1.EditIndex = -1. 2. 3.EditIndex = -1. e) { GridView1. 2. It’s me .164 - . GrdBind(). Window AuthenticationIt is by default authentication. 4. Forms (a).Text). GridView1. Passport Authentication with single sign in we can login into multiple passport Enable sites. } protected void GridView1_RowCancelingEdit(object. Window Integrating AuthenticationUser of window. GrdBind(). Basic Authentication  In basic authentication user password stored into cleared text. 3.

Data.Text.Text == "khan") { FormsAuthentication.Web. } else { Response. using System. using System.Web.Web. using System.UI.aspx"></forms> </authentication> Login.Membership and role is a new feature in 2.Page { protected void Page_Load(object sender.165 - .UI.UI. using System.Add webconfig file Username Password Button Webconfig file <authentication mode="Forms"> <forms name="cookie" loginUrl="login. } } } It’s me . using System. using System.Web.HtmlControls.UI.Write("Wrong user/password").Web.Collections.Web.UI.RedirectFromLoginPage (TextBox1.WebControls. using System. EventArgs e) { if (TextBox1.false).0 FORM AUTHENTICATION 1. using System.Security. using System.WebParts.WebControls.Configuration. EventArgs e) { } protected void Button1_Click(object sender.aspx using System. public partial class login : System.Text == "faisal" && TextBox2.Web.

FormsAuthentication. using System.UI. using System.UI.Web. using System.false)user name ko cookie mai likhega aur redirect to default page.aspx It’s me .Text. using System.RedirectToLoginPage().Text = "Welcome :" + User.UI.aspx"> <credentials passwordFormat ="Clear"> <user name ="admin" password ="ad"/> <user name ="admin1" password ="ad1"/> </credentials> </forms> </authentication> Login.IsAuthenticated) { Label1.WebControls.RedirectFromLoginPage(TextBox1. using System.Web.Data. public partial class _Default : System. EventArgs e) { if (User.Security.Web. using System.aspx Label using System. } else { FormsAuthentication.166 - .HtmlControls.Configuration.Identity.Web.WebParts.Page { protected void Page_Load(object sender.WebControls.UI.Web.UI.Web.Name. using System. } } } HOW USER AUTHENTICATE IN WEB CONFIG FILE Webconfig file <authentication mode="Forms"> <forms name="cookie" loginUrl="login.Web.Identity. Default. using System.

aspx"> <system.Text)) { FormsAuthentication. It’s me . } } Specific Autherity </system. EventArgs e) { if (FormsAuthentication.Username Password Button2 protected void Button2_Click(object sender.167 - . false).Authenticate(TextBox1.Write("Wrong user/password").web > <authorization > <allow users ="admin"/> <deny users ="*"/> </authorization> </system. ? Means deny unauthenticated.aspx"> <system.Text.web > <authorization > <allow users ="admin1"/> <deny users ="*"/> </authorization> </system. TextBox2.RedirectFromLoginPage(TextBox1. } else { Response.web> </location> * Means deny autherisation and unautherisation user.web> </location> <location path ="default3.Text.web> <location path ="default2.

aspx Roles assign to folder in webconfigfile • Add webconfig file <authentication mode="Forms"> <forms name="cookie" loginUrl="login.aspx 2 hyperlink button PropertyNavigationURLDefault2.default3.default5.aspx Usr-->default4.168 - .web> <location path ="adm"> <system.aspx.web > <authorization > It’s me .aspx"> </forms> </authentication> </system.aspx ROLE BASED SECURITY Create table tbusr • • • Uname Faisal Sachin Charu • • Uname varchar(50) Upass varchar(50) Urole varchar(50) Upass khan gupta satia Urole admin user admin|user Add some record eg Add 2 folder in solution explorer Adm--> default2.aspx PropertyNavigationURLDefault3.aspx.Default.

50).web> </location> Login.Page { protected void Page_Load(object sender. cmd. cmd. dr = cmd.Parameters.HasRows) It’s me . cmd. con.CommandText = "select * from tbauth1 where uname=@u and upass=@p". if (dr.web > <authorization > <allow roles ="user"/> <deny users ="*"/> </authorization> </system.Connection = con. SqlCommand cmd = new SqlCommand().169 - . public partial class login1 : System.Add("@u".UI.SqlClient.Web.Parameters.aspx Username Password Button using System.VarChar.Value =TextBox2. cmd. EventArgs e) { } protected void Button1_Click(object sender.<allow roles ="admin"/> <deny users ="*"/> </authorization> </system. EventArgs e) { SqlConnection con = new SqlConnection(). con.Data.Text. 50). SqlDbType.uid=sa". SqlDbType. SqlDataReader dr.Add("@p".ConnectionString = "database=emp.Text.Value =TextBox1.Open().web> </location> <location path ="usr"> <system.VarChar.ExecuteReader().

Close().FormsCookiePath).Dispose(). It’s me . 3rd Parameter issued ticket datetime 4th Parameter expire time 5th Parameter cookies temp(false) or permanent(untill web browser session expire).Now.Read(). FormsAuthenticationTicket tkt = new FormsAuthenticationTicket(1.aspx string st.FormsCookieName. Response.Encrypt(tkt). TextBox1.{ dr. FormsAuthentication.ToString(). } dr. } else { Response. HttpCookie ck = new HttpCookie(FormsAuthentication. false. 2nd Parameter username.Text. cmd.Now. DateTime. //Here we encrypt the ticket n stored st(ticket) and cookie name from webconfig file into cookie or with the help of querystring passed this value into default.170 - . st). dr[2]. st = FormsAuthentication.aspx"). DateTime. 7th Parameter string cookies path. 1st Parameter is ticket version no. } } • • • • • • • • FormsAuthenticationTicket tkt  Ticket is used for passing customise data whatever we want.Add(ck).Write("wrong user/password").Redirect("default.AddMinutes(10). Response. 6th Parameter string userdata dr[2] contain table coloumn Urole. assign with multiple tickets.Cookies.

How authenticate user access the file so a Add global application class Global Application Class Namespace System. EventArgs e) { // Code that runs on application shutdown } void Application_Error(object sender.config file. EventArgs e) { // Code that runs when a new session is started } void Session_End(object sender. EventArgs e) { // Code that runs on application startup } void Application_End(object sender.Principal"%> <script runat="server"> void Application_Start(object sender. //We get current user identity(ticket) It’s me . <%@ Application Language="C#" %> <%@ Import Namespace ="System. // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web.Security. EventArgs e) { // Code that runs when an unhandled error occurs } void Session_Start(object sender.User!= null) { FormsIdentity fi. the event is not raised. } protected void Application_AuthenticateRequest(object sender.EventArgs e) { if (HttpContext. HttpContextEnclupulate all http specific information about an individual http request.Current.171 - .Security. EventArgs e) { // Code that runs when a session ends.Principal contain generic principal class which is combination of identity & roles is known as generic principal. If session mode is set to StateServer // or SQLServer. Select application and his event AuthenticateRequest . Event AuthenticateRequest fire every time for user check.

UserData.Current.Split('|'). } } </script> Default.aspx 2 Hyperlink Button PropertyNavigationURLadm/Default2.aspx. = (FormsIdentity)(User.aspx PropertyNavigationURLusr/Default4.172 - .Default3. //Get user role with ticket. //fi contain identity of user and array ar contain role which is known as generic principal.aspx.aspx It’s me .Identity). FormsAuthenticationTicket tk. string ud = tk. tk = fi. ar).User = new GenericPrincipal(fi.Default5. split the role and stored into array. string[] ar = ud.

173 - .It’s me .

Sign up to vote on this title
UsefulNot useful