Dr. Minder Chen - PowerPoint PPT Presentation

1 / 199
About This Presentation
Title:

Dr. Minder Chen

Description:

Panel1.Visible = True. LabelName.Text = Request.Params.Get('UserName') Dim prog as String ... asp:Panel id='Panel1' runat='server' Visible='False' ... – PowerPoint PPT presentation

Number of Views:378
Avg rating:3.0/5.0
Slides: 200
Provided by: MCh591
Category:
Tags: chen | minder | panel1

less

Transcript and Presenter's Notes

Title: Dr. Minder Chen


1
MIS 412 E-Business Systems Development Fall
2006
Using ASP.NET
Dr. Minder Chen Associate Professor and Area
Coordinator of Decision Science and MIS George
Mason University Email mchen_at_gmu.edu 703-993-178
8
Fall 2006
2
ASP.NET
  • Teaching Materials Resources
  • Visual Web Developer Express as a Web Development
    Tool
  • HTML Form Data Handling The Traditional Approach
  • Event-Driven Programming Model Web Server
    Controls and Post-back
  • State Management Session, Cookie, etc.
  • Basic Web Database Programming Using ADO.NET
  • New Features in ASP.NET 2.0
  • ASP.NET 2.0 Style Database Programming Data
    Source Controls and New Data-Bound Controls
    (GridView, DetailsView, FormView)
  • Master Page, Navigation, Theme, UI Tips
  • A Simple Shopping Cart Example

3
Resources
  • Web site
  • My ASP.NET course Web site http//gunston.gmu.edu
    /ecommerce/ebiz/
  • Microsoft official site http//www.asp.net
  • Tutorial http//www.asp.net/QuickStart/aspnet/Def
    ault.aspx
  • http//msdn.microsoft.com/asp.net/community/author
    s/stephenwalther/default.aspx by Stephen Walther
  • Download Visual Web Developer
  • http//msdn.microsoft.com/vstudio/express/vwd/defa
    ult.aspx
  • Books
  • Murach's ASP.NET 2.0 Web Programming with VB 2005
    (Paperback) by Anne Boehm, Doug Lowe, 2006. (text
    book)
  • Beginning ASP.NET 2.0 by Chris Hart, John
    Kauffman, David Sussman, and Chris Ullman
    (Paperback - Nov 10, 2005)
  • Murach's ASP.NET Web Programming with VB.NET
    (Paperback), by Doug Lowe, Anne Prince, 2003.
  • ASP.NET 2.0 Unleashed (Paperback) by Stephen
    Walther

4
.NET Framework
VB.NET
C
C
JScript
J
Visual Web Developer Visual Studio .NET
Common Language Specification
ASP.NET Web Forms Web Services Mobile Forms
Windows Forms
ADO.NET and XML
Base Class Library
Common Language Runtime
Operating System
5
Visual Web Developer Express as a Web Development
Tool
  • Visual Studio .NET 2002
  • Visual Studio .NET 2003
  • Web Matrix
  • Visual Web Developer
  • Visual Studio .NET 2005
  • Additional software products
  • SQL Server Express 2005
  • SQL Server 2005
  • Access
  • Deployment
  • Windows server 2003 running IIS
  • .NET Framework SDK

6
Form Handling No Web Server Control
  • lt_at_ Page Language"VB" gt
  • lt!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
    Transitional//EN" "http//www.w3.org/TR/xhtml1/DTD
    /xhtml1-transitional.dtd"gt
  • lthtml xmlns"http//www.w3.org/1999/xhtml" gt
  • lthead runat"server"gt
  • lttitlegtUntitled Pagelt/titlegt
  • lt/headgt
  • ltbodygt
  • ltform id"form1" gt
  • Enter your name
  • ltinput id"Text1" name"username"
    type"text" /gt
  • ltinput id"Submit1" type"submit"
    value"submit" /gt
  • lt Response.Write("Hello ltbgt" _
  • Request.Params.Get("username")
    "lt/bgt")gt
  • lt/formgt
  • lt/bodygt
  • lt/htmlgt

Submit to the form itself (Postback) since there
is no action attribute
Mixing HTML and Server side scripting code
7
Form Processing
8
Registration.htm
  • lthtmlgt
  • ltheadgt
  • lt/headgt
  • ltbodygt
  • lth1gtRegistration Form
  • lt/h1gt
  • ltform action"registration.aspx"
    method"post"gt
  • Name
  • ltinput type"text" name"username" /gt
  • ltpgt
  • Password
  • ltinput type"password" name"psw" /gt
  • lt/pgt
  • ltpgt
  • ltinput type"checkbox"
    name"programming" /gtnbspHave programming
    experience
  • lt/pgt
  • ltfieldset style"WIDTH 646px HEIGHT
    91px"gt
  • ltlegend title"Test"gtChoose Favorite
    Colorlt/legendgt
  • ltinput type"radio" value"1"
    name"color" /gtRedltbr /gt

9
Continued
  • ltpgt
  • Select all your skills
  • lt/pgt
  • ltselect title"Use CTL key to select more
    than one item"
  • style"HEIGHT 54px" multiple"multiple"
    size"3" name"skills"gt
  • ltoption value"db" selected"selected"
    gtDatabaselt/optiongt
  • ltoption value"wp"gtWeb
    programminglt/optiongt
  • ltoption value"sa"gtAnalysis and
    designlt/optiongt
  • ltoption value"ec"gtElectronic
    Commercelt/optiongt
  • lt/selectgt
  • ltpgt
  • Your comment
  • ltbr /gt
  • lt/pgt
  • lttextarea name"comment" rows"5"
    cols"44"gtlt/textareagt
  • ltpgt
  • ltinput type"submit" value"Submit"
    /gtnbspnbspnbspnbsp
  • ltinput type"reset" value"Reset" /gt
  • lt/pgt

10
Registration.aspx
  • lt_at_ Page Language"VB" gt
  • ltscript runat"server"gt
  • Public Enum Colors
  • Red 1
  • Blue 2
  • Green 3
  • End Enum
  • Sub Page_Load()
  • If Request.Params.Get("UserName").Trim() ltgt
    Request.Params.Get("PSW").Trim() Then
  • LabelMsg.Text "Your user name and
    password do not match. Please go back to " _
  • "previous page. ltinput typebutton value'Go
    Back' onClick'history.back()'gt"
  • Exit Sub
  • End If
  • Panel1.Visible True
  • LabelName.Text Request.Params.Get("UserNam
    e")
  • Dim prog as String
  • prog Request.Params.Get("programming")
  • If prog "on" Then
  • LabelProgramming.Text "Yes"

11
Continued
  • Dim skillset as String()
  • Dim skill as String
  • skillset Request.Params.GetValues("skills"
    )
  • If skillset is Nothing Then
  • LabelSkill.Text "You do not have any
    skill!"
  • Else
  • For each skill in skillset
  • LabelSkill.Text skill "ltbrgt"
  • Next
  • End if
  • Dim UserComment as String
  • UserComment Request.Params.Get("comment")
  • LabelComment.Text replace(UserComment,
    Microsoft.VisualBasic.ControlChars.CrLf, "ltbrgt")
  • Dim myColor as Integer
  • ' LabelColor.Text Request.Params.Get("col
    or")
  • myColor CType(Request.Params.Get("color"),
    Integer)
  • Select Case myColor
  • Case Colors.Red
  • LabelColor.Text Colors.Red.ToString()

12
Continued
  • lthtmlgtltheadgtlt/headgtltbodygt
  • ltform id"Form1" runat"server"gt
  • lth1gtSubmission Confirmation
  • lt/h1gt
  • ltpgt
  • ltaspLabel id"LabelMsg"
    runat"server"gtlt/aspLabelgt
  • lt/pgt
  • ltaspPanel id"Panel1" runat"server"
    Visible"False"gt
  • Your name is ltaspLabel
    id"LabelName" runat"server"gtlt/aspLabelgt
  • ltpgt
  • You like programming ltaspLabel
    id"LabelProgramming" runat"server"gtlt/aspLabelgt
  • lt/pgt
  • ltpgt
  • Your skills include ltbr /gt
  • ltaspLabel id"LabelSkill"
    runat"server"gtlt/aspLabelgt
  • lt/pgt
  • ltpgt
  • The color your like is ltbr /gt
  • ltaspLabel
    id"LabelColor" runat"server"gtlt/aspLabelgt

13
Navigating Between Web Pages
  • Hypertext links with QueryString (URL variables)
  • Form submission
  • Request.Redirect()
  • Server.Transfer() -- Doesn't work!
  • Server.Execute() -- Rarely used!
  • Windows.Open() -- Client-side JavaScript!

14
Hypertext Links and Forms
  • Hypertext link
  • lta href"URL?x3yHello"gtNextlt/agt
  • Standard HTML Forms
  • ltform action"URL" method"post"gt
  • Form elements
  • lt/formgt

QueryString
Post Send form data as standard input Get Send
form data as QueryString
  • URL of the form handling page.
  • In ASP.NET, when you use Web form contriols, the
    action is to submit to the form itself, i.e.,
    PostBack

15
Request.Params
  • Gets a combined collection of QueryString, Form,
    ServerVariables, and Cookies items.
  • Request.Params.Get("name")
  • Gets the values of a specified entry in the
    NameValueCollection combined into one
    comma-separated list.
  • A String is return.
  • Request.Params.GetValues("name")
  • Gets the values of a specified entry in the
    NameValueCollection.
  • An array of String is returned.

16
Create a New Web Site
17
Creating a New Page
18
Select a Web Form
19
(No Transcript)
20
Toolbox Web Server Controls
21
Properties Window
22
(No Transcript)
23
Create an Event Procedure
  • Double click on a Web Server Control
  • Determine the event to be associated with the
    control
  • Write appropriate code for responding to the event

24
Set a Breakpoint for Debugging
  • Click on the sideline of the corresponding code
    line to set the breakpoint
  • Click again to remove the breakpoint

25
Set as Start Page
  • Your project/web site may contain many Web forms.
  • When you try to run and test a specific Web page,
    you should set that page to be the Start page.
  • Right mouse button click on the page, choose "Set
    As Start Page" from the pop-up menu

26
Running and Debugging your Web Form
27
Web.config file
  • You need to Add a new Web.config file for the
    whole Web site / Web application

28
Web.config
29
Web Application Administration
  • Hand editing this file or use the web admin tool
    to configure settings for your application. Use
    the Website-gtAsp.Net Configuration option in VWD
  • A full list of settings and comments can be found
    in machine.config.comments usually located in
    \Windows\Microsoft.Net\Framework\v2.x\Config

30
Running the Web page
31
Debugging Functions
32
Error List
  • If you double click on a Web server control, an
    event procedure for the control will be created.
    When you use the single file format, then if you
    delete the procedure without deleting the
    reference to it in the Web server control (such
    as OnTextChanged"TextBox1_TextChanged" attribute
    below), an error will occur during compilation.
    If you use code behind, this will not be a
    problem.
  • Enter Your Name
  • ltaspTextBox ID"TextBox1" runat"server"
    OnTextChanged"TextBox1_TextChanged"gt
  • lt/aspTextBoxgt

Just say NO!
Include all errors from Web forms in the Web site
33
(No Transcript)
34
Add Watch
  • Highlight a variable, an object, or a property
  • Right mouse button click to select the "Add
    Watch" from the menu

Click here if you are looping through this
variable the second time during debugging to
update the current value.
35
Page Load Event
  • Page Load event will be executed every time you
    access the page.
  • Web server controls' events always post back to
    the page itself.
  • Use IsPostBack function to determine whether it
    is the first request of the page or a post back
    to the page.

Postback
ASP.NET page's ltform runat"server"gt tag does not
have the action attribute, therefore all Web
server controls event will send the form
variables (i.e., Web server controls' data) to
the same page to be processed by corresponding
server-side event-handling methods.
36
PostBack
  • ltscript runat"server"gt
  • Protected Sub Page_Load(ByVal sender As
    Object, ByVal e As System.EventArgs)
  • If IsPostBack Then
  • LabelWelcome.Text "Thank you, "
    TextBox1.Text _
  • " for using Hello World!"
  • Else
  • LabelWelcome.Text "Welcome to my
    Hello World!"
  • End If
  • End Sub
  • Protected Sub Button1_Click(..)
  • Label1.Text "Hello " TextBox1.Text
  • End Sub
  • lt/scriptgt

37
Page/Control Event Execution
PostBack
First Request
For a particular user visits an ASP.NET page
Page DLL is loaded, control hierarchy initialized
They may be triggered on PostBack
Page_Load
Textbox1_Changed
1. Change Events
Button1_Click
2. Action Events
Control hierarchy (Dynamically generated HTML
page) is rendered
Page_PreRender Page_Unload
Page is disposed
38
ASP.NET Pages Part Declarative, Part Code
  • Combines declarative tags (HTML, ASPX directives,
    server controls tags, and static text) with code
    in a single file or in separate files.
  • Unlike ASP, good separation provided between code
    and tags.
  • VWD and VS 2005 support intelli-sense and
    debugging with single-file format.

?
single file
separate files (code-behind)
code
code
lttagsgt
lttagsgt
Form1.aspx
Form1.aspx
Form1.aspx.vb
39
Control Event Processing
  • Events are
  • Triggered on the client by the user
  • Handled in server code
  • Requires a postback to the same page
  • ViewState of controls saves page and control
    properties between round trips, therefore helps
    restore control to its previous state.
  • Implemented as a hidden form field
  • Disable via setting the EnableViewState attribute
  • EnableViewStatefalse
  • Data Binding resets control state

40
ViewState and PostBack
Hello2.aspx.vb If Not IsPostBack
Hello2.aspx
ltasptextbox id"TextBox1" runat"server" /gt
Minder Chen
States of a page is maintained via the ViewState
between the Postback
41
Web Form Design/Development Process
  • Paint/design Web form
  • What Web server controls to use
  • Set their some of their properties to certain
    values
  • Define the dynamic behaviors of the Web form
  • Determine what events associated with these
    controls need to be written
  • Click event of the Button1
  • Write the code to to handle the click event of
    Button1, i.e., Button1_click()
  • Test the Web form

42
RadioButtonList.aspx runtime
43
Web Form Designer
Checkbox with AutoPostBack
RadioButtonList
Panel Visible False
44
Set Up Properties of Web Server Controls
45
Define Items in RadioButtonList control
46
RadioButtonList.aspx
  • lt_at_ Page Language"VB" gt
  • lt!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http//www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"gt
  • ltscript runat"server"gt
  • Protected Sub Button1_Click(ByVal sender As
    Object, ByVal e As System.EventArgs)
  • If CheckBox1.Checked Then
  • Label1.Text "You know ASP.NET 2.0
    ltbrgt"
  • Label1.Text "Your level of
    expertise is " RadioButtonList1.SelectedItem.Te
    xt _
  • "ltbrgt"
  • Label1.Text "Your level of
    expertise code is " RadioButtonList1.SelectedVa
    lue
  • Else
  • Label1.Text "You don't know ASP.NET
    2.0 ltbrgt"
  • End If
  • End Sub
  • Protected Sub CheckBox1_CheckedChanged (ByVal
    sender As Object, ByVal e As System.EventArgs)
  • If CheckBox1.Checked Then
  • Panel1.Visible True
  • Else
  • Panel1.Visible False
  • End If

Panel1.Visible Not Panel1.Visible
47
Code -- Continued
  • lthtml xmlns"http//www.w3.org/1999/xhtml" gt
  • lthead runat"server"gt
  • lttitlegtRadioButtonList lt/titlegt
  • lt/headgtltbodygt
  • ltform id"form1" runat"server"gt
  • ltdivgt
  • ltstronggtltspan style"font-size
    14pt"gtAuto Postback Checkbox
    DadioButtonListnbspltbr /gt
  • ltbr /gt
  • ltaspCheckBox ID"CheckBox1"
    runat"server" AutoPostBack"True" Text"I know
    ASP.NET 2.0"
  • OnCheckedChanged"CheckBox1_CheckedChanged"
    /gtltbr /gt ltbr /gt
  • lt/spangtlt/stronggt
  • ltaspPanel ID"Panel1" runat"server"
    BorderStyle"Outset" Height"136px"
    Visible"False" Width"256px"gt
  • ltstronggtChoose your level of
    expertise in ASP.NET 2.0 lt/stronggt ltbr /gt
  • ltaspRadioButtonList ID"RadioButtonList1"
    runat"server" Font-Bold"True" gt
  • ltaspListItem Selected"True"
    Value"1"gtBasiclt/aspListItemgt
  • ltaspListItem Value"2"gtIntermediatelt/
    aspListItemgt
  • ltaspListItem Value"3"gtAdvancedlt/asp
    ListItemgt
  • lt/aspRadioButtonListgt
  • lt/aspPanelgt

48
Runtime Compilation
First Request after the deployment
ASPX File
49
Major Build-in ASPX Objects
  • Request Object
  • Cookies
  • Form
  • QueryString
  • ServerVariables
  • ClientCertificate
  • Response Object
  • Cookies
  • (Properties)
  • (Methods)

S e r v e r
C l i e n t
  • Server Object
  • (Properties)
  • (Methods)

Application Object Session Object Cache Object
50
ASP Application and Session Objects
I I S
ASP.NET
Application Object 1
Application Object 2
Application Object 3
Session Object 1
Session Object 1
Session Object 1
Session Object 2
Session Object 2
Session Object 2
Session Object 3
Session Object 3
Session Object 3
51
Session Object and ViewState Object
  • Session ("UserName") "John" ' in page1
  • Response.Write(Session("UserName")) ' in page2
  • This will store the string "John" in the Session
    object and give it the name "UserName."
  • This value can be retrieved from the Session
    object by referencing the Session object by name,
    as in the following
  • ViewState("t1") "Test"
  • Dim s as String
  • S ViewState("t1") ' ViewState("T1") is a
    different variable!
  • You can only store a string in a cookie and in a
    ViewState variable.
  • The ViewState variable names are case sensitive.
  • See Online Help on "Saving Web Forms Page Values
    Using View State"

52
Store Objects as Session Variables in the Session
Object
  • You may want to use CType() function to cast
    session variable back to an appropriate object
    before you use it.
  • In page1.asx
  • Dim x1 as New ClassX()
  • Session("sv_x") x1
  • In page2.aspx
  • Dim x2 as New ClassX()
  • x2 CType(Session("sv_x"), ClassX)

53
Using Session Objects
  • You can use the Session object to store
    information needed for a particular user-session.
  • Variables stored in the Session object are not
    discarded when the user jumps between pages in
    the application instead, these variables persist
    for the entire user-session.
  • The Web server automatically creates a Session
    object when a Web page from the application is
    requested by a user who does not already have a
    session.
  • The server destroys the Session object when the
    session expires or is abandoned.
  • One common use for the Session object is to store
    user preferences.

54
Session Variables
  • Logon.aspx

Session2.aspx
55
Logon.aspx
  • lt_at_ Page Language"vb" AutoEventWireup"false"
  • Codebehind"logon.aspx.vb" Inherits"exstate.Log
    on"gt
  • lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
    Transitional//EN"gt
  • ltHTMLgt
  • ltHEADgtlttitlegtsession1lt/titlegtlt/HEADgt
  • ltbodygt
  • ltform id"Form1" method"post"
    runat"server"gt
  • ltPgtUser name
  • ltaspTextBox id"TextBoxUserID"
    runat"server"gtlt/aspTextBoxgtlt/Pgt
  • ltPgtPassword
  • ltaspTextBox id"TextBoxPassword"
    runat"server" TextMode"Password"gt
    lt/aspTextBoxgtlt/Pgt
  • ltPgtFirst name
  • ltaspTextBox id"TextBoxFirst"
    runat"server"gtlt/aspTextBoxgtlt/Pgt
  • ltPgtLast Name
  • ltaspTextBox id"TextBoxLast"
    runat"server"gtlt/aspTextBoxgtlt/Pgt
  • ltPgtltaspButton id"Button1"
    runat"server" Text"Submit"gtlt/aspButtongtlt/Pgt
  • ltPgtltaspLabel id"LabelMsg"
    runat"server"gtlt/aspLabelgtlt/Pgt
  • lt/formgt
  • lt/bodygt

56
Logon.aspx.vb
  • Public Class Logon
  • Inherits System.Web.UI.Page
  • Protected WithEvents TextBoxUserID As
    System.Web.UI.WebControls.TextBox
  • Protected WithEvents TextBoxFirst As
    System.Web.UI.WebControls.TextBox
  • Protected WithEvents TextBoxLast As
    System.Web.UI.WebControls.TextBox
  • Protected WithEvents Button1 As
    System.Web.UI.WebControls.Button
  • Protected WithEvents LabelMsg As
    System.Web.UI.WebControls.Label
  • Protected WithEvents TextBoxPassword As
    System.Web.UI.WebControls.TextBox
  • Region " Web Form Designer Generated Code "
  • '
  • End Region
  • Private Sub Page_Load(ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles MyBase.Load
  • LabelMsg.Text "" ' Reset Message
  • If Not IsPostBack Then
  • If Request.Params.Get("msg")
    "userid" Then
  • LabelMsg.Text "Please login
    before you visit other pages on this site."
  • End If
  • End If
  • End Sub

57
Continued
  • Private Sub Button1_Click (ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles Button1.Click
  • Dim NewUser As New User()
  • If TextBoxUserID.Text ltgt "" Then
  • If Check(TextBoxUserID.Text,
    TextBoxPassword.Text) Then
  • Session("UserID")
    TextBoxUserID.Text
  • NewUser.FirstName
    TextBoxFirst.Text
  • NewUser.LastName
    TextBoxLast.Text
  • Session("UserName") NewUser
  • Response.Redirect("session2.aspx")
  • Else
  • LabelMsg.Text "Your user id and
    password does not match what is in our file"
  • End If
  • Else
  • LabelMsg.Text "You need to enter
    your user id"
  • End If
  • End Sub
  • Private Function Check(ByVal user As String,
    ByVal pswd As String) As Boolean
  • If user pswd Then

58
User Class
  • Public Class User
  • Public FirstName As String
  • Public LastName As String
  • End Class

59
Sesison2.aspx
  • lt_at_ Page Language"vb" AutoEventWireup"false"
  • Codebehind"Session2.aspx.vb" Inheritscode.Sess
    ion2"gt
  • lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
    Transitional//EN"gt
  • ltHTMLgt
  • ltHEADgt
  • lttitlegtSession2lt/titlegt
  • lt/HEADgt
  • ltbodygt
  • ltform id"Form1" method"post"
    runat"server"gt
  • ltPgtHi
  • ltaspLabel id"LabelFirstName"
    runat"server"gtlt/aspLabelgt
  • ltaspLabel id"LabelLastName"
    runat"server"gt lt/aspLabelgtlt/Pgt
  • ltPgtYour User ID is
  • ltaspLabel id"LabelUserID"
    runat"server"gtlt/aspLabelgtlt/Pgt
  • lt/formgt
  • lt/bodygt
  • lt/HTMLgt

CodeFile
60
Session2.aspx.vb
  • Public Class Session2
  • Inherits System.Web.UI.Page
  • Protected WithEvents LabelFirstName As
    System.Web.UI.WebControls.Label
  • Protected WithEvents LabelLastName As
    System.Web.UI.WebControls.Label
  • Protected WithEvents LabelUserID As
    System.Web.UI.WebControls.Label
  • Region " Web Form Designer Generated Code "
  • ' ..
  • End Region
  • Private Sub Page_Load (ByVal sender As
    System.Object, ByVal e As System.EventArgs)
    Handles MyBase.Load
  • LabelUserID.Text Session("UserID")
  • Dim CurrentUser As New User()
  • If Session("UserName") Is Nothing Then
  • Response.Redirect("Logon.aspx?msguser
    id")
  • Else
  • CurrentUser CType(Session("UserName"
    ), User)
  • LabelFirstName.Text
    CurrentUser.FirstName
  • LabelLastName.Text
    CurrentUser.LastName
  • End If
  • End Sub

61
Cookieless Session
Web.config
  • InProc
  • StateServer
  • SQLServer
  • ltconfigurationgt
  • ltsystem.webgt
  • ltsessionState
  • mode"InProc"
  • stateConnectionString"tcpip127.0.0.142424
    "
  • sqlConnectionString"data
    source127.0.0.1user idsapassword"
  • cookieless"true"
  • timeout"20"
  • /gt
  • lt/configurationgt
  • lt/system.webgt

Default value is false
  • All the URL to pages in the web site must use
    document relative URLs.
  • You cannot use absolute URLs or root relative
    URLs,
  • such as lta href"/abc/page1.aspx"gtTestlt/agt

62
Basic Web Database Programming Using ADO.NET
  • Select
  • Stored procedure

Client Application
Read
DataReader
Command
Windows Form
Connection
Write
Command
  • Insert
  • Update
  • Delete
  • Stored procedure

Web Form
Database
63
Cursor of a "Record Set"
Dim dr As OleDbDataReader dr
catCMD.ExecuteReader()
Column index
0 1 2
Num Name Price
Initial position of cursor
Column name
100 Java 200.00
200 HTML 250.00
300 C 300.00
400 XML 240.00
Current cursor position
dr.read() moves the cursor to the next row and
return True if the next row exists.
If current cursor position is here, then the
execution of dr.read() returns False.
Record set
64
Accessing Column Values
By Zero-based Column Type Safe or Ordinal Reference By Column Name String Reference Returned Value
dr.getInt32(0) or dr(0) dr("Num") 200
dr.getString(1) or dr(1) dr("Name") HTML
dr.getDecimal(2) or dr(2) dr("Price") 250.00
  • Accessing the value of a column from the current
    record in the record set, e.g., dr, you can use
    either dr(i) where i is an ordinal reference (0,
    1, 2, ...) or dr("ColumnName").  
  • It will return an object and when it is used for
    output, it is implicitly converted to string data
    type. 
  • If you want to use Type Safe Reference, you can
    use dr.GetXXX(i) where i is an ordinal reference
    (0, 1, 2, ...) and XXX is the appropriate data
    type of the column such as dr.GetDecimal(2).  
  • Type Safe Reference is more convenient when you
    want to format the retrieved data or to use it in
    a calculation.  You cannot use column names with
    Type Safe Reference. 

dr.getDecimal("Price") is illegal!
65
Commonly Used DataReader Properties and Methods
66
Categories Table in NorthWind Access Database
67
CategoryList.aspx
68
Using DataReader
Dynamically generated web page
2
Format result set rows in HTML format
Category table
1
SQL statement
NorthWind
ASP.NET Code
5
Record set
100




DataReader
Retrieve result set, one row at a time.
100




4
3
69
CategoryList.aspx
  • lt_at_ Page Language"VB" gt
  • lt_at_ Import Namespace"System.Data.OleDB" gt
  • lt_at_ Import Namespace"System.Data" gt
  • lt!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http//www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"gt
  • ltscript runat"server"gt
  • Protected Sub Page_Load (ByVal sender As
    Object, ByVal e As System.EventArgs)
  • Dim conn As OleDbConnection
  • Dim cmd As OleDbCommand
  • Dim dr As OleDbDataReader
  • conn New _
  • OleDbConnection("PROVIDERMicrosoft.Jet.
    OLEDB.4.0" _
  • "Data Source"
    Server.MapPath("Northwind.mdb"))

70
CategoryList.aspx - continued
  • If Not IsPostBack Then
  • Try
  • conn.Open()
  • cmd New OleDbCommand("select
    from categories", conn)
  • cmd.CommandType
    CommandType.Text
  • dr cmd.ExecuteReader()
  • While dr.Read()
  • Label1.Text dr.GetInt32(0)
    "--" _
  • dr.GetString(1)
    "--" _
  • dr.GetString(2)
    "ltbrgt"
  • End While
  • Catch ex As Exception
  • Label1.Text "Database error!"
    "ltbrgt" ex.Message
  • Finally
  • conn.Close()
  • End Try
  • End If
  • End Sub
  • lt/scriptgt

71
CategoryList.aspx - continued
  • lthtml xmlns"http//www.w3.org/1999/xhtml" gt
  • lthead runat"server"gt
  • lttitlegtADO.NET Example - 1lt/titlegt
  • lt/headgt
  • ltbodygt
  • ltH1gtList of categorieslt/H1gt
  • ltform id"form1" runat"server"gt
  • ltdivgt
  • ltaspLabel id"Label1" runat"server"gtlt/aspLa
    belgt
  • lt/divgt
  • lt/formgt
  • lt/bodygt
  • lt/htmlgt

72
Run-Time
73
InsertProduct.aspx
  • lt_at_ Page Language"VB" gt
  • lt_at_ Import Namespace"System.Data.OleDB" gt
  • lt_at_ Import Namespace"System.Data" gt
  • lt!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http//www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"gt
  • ltscript runat"server"gt
  • Protected Sub ButtonInsert_Click(ByVal sender
    As Object, ByVal e As System.EventArgs)
  • Dim OleDbInsertCommand1 As New
    OleDbCommand()
  • Dim OleDbConnection1 As New
    OleDbConnection()
  • Dim OleDbSelectCommand1 As New
    OleDbCommand()

74
Continued
  • Try
  • OleDbInsertCommand1.CommandText _
  • "INSERT INTO Products(ProductName, CategoryID,
    UnitPrice, Discontinued) VALUES (" _
  • "'" TextBoxProductName.Text "'," _
  • TextBoxCategoryID.Text "," _
  • TextBoxUnitPrice.Text "," _
  • CheckBoxDiscontinued.Checked ")"
  • OleDbConnection1.ConnectionString _
  • "ProviderMicrosoft.Jet.OLEDB.4.0Password''
    User IDAdmin" _
  • "Data Source" Server.MapPath("Northwind.mdb
    ")
  • OleDbConnection1.Open()
  • OleDbInsertCommand1.Connection
    OleDbConnection1
  • Dim NumInserted As Integer
  • NumInserted OleDbInsertCommand1.ExecuteNon
    Query()

Replace(aString,"'","''") Replace the values
that are string in SQL Statement.
75
Continued
  • If NumInserted 1 Then
  • LabelMessage.Text "New record
    has been created successfully!"
  • OleDbSelectCommand1.CommandText
    _
  • "select max(ProductId) from Products Where
    Productname " _
  • "'" TextBoxProductName.Text
    "'"
  • OleDbSelectCommand1.Connection
    OleDbConnection1
  • Dim MaxProductId As Integer
  • MaxProductId OleDbSelectCommand1
    .ExecuteScalar()
  • LabelMessage.Text _
  • "ltbrgtThe Product Number for this product is "
    MaxProductId
  • Else
  • LabelMessage.Text "Insert
    Fail!"
  • End If
  • Catch ex As Exception
  • LabelMessage.Text "Database Error!
    Insert Failed! " ex.Message
  • Finally
  • OleDbConnection1.Close()
  • End Try
  • End Sub

76
Continued
  • lthtml xmlns"http//www.w3.org/1999/xhtml" gt
  • lthead runat"server"gt
  • lttitlegtUntitled Pagelt/titlegt
  • lt/headgt
  • ltbodygt
  • ltform id"form1" runat"server"gt
  • ltPgtltFONT size"5"gtltSTRONGgtInsert
    Productlt/STRONGgtlt/FONTgtlt/Pgt
  • ltPgtProduct Name
  • ltaspTextBox id"TextBoxProductName"
    runat"server"gtlt/aspTextBoxgtlt/Pgt
  • ltPgtCategory ID
  • ltaspTextBox id"TextBoxCategoryID
    " runat"server"gtlt/aspTextBoxgtlt/Pgt
  • ltPgtPrice
  • ltaspTextBox id"TextBoxUnitPrice"
    runat"server"gtlt/aspTextBoxgtlt/Pgt
  • ltPgtltaspCheckBox id"CheckBoxDiscontinued"
    runat"server"
  • Text"Discontinued"gtlt/aspCheckBoxgtnbsplt/Pgt
  • ltPgtltaspButton id"ButtonInsert" runat"server"

77
Using Parameterized SQL
  • .
  • Dim Desc as String
  • Desc Textbox1.Text
  • cmd2.CommandText _
  • "INSERT INTO ImportedItem (Description,
    ActivityID) VALUES (?, 1)"
  • cmd2.Parameters.Clear()
  • cmd2.Parameters.Add("Description", Desc)
  • cmd2.ExecuteNonQuery()
  • ..

No need to use Replace function for string values
Soruce http//www.4guysfromrolla.com/webtech/0926
01-1.2.shtml
78
Use Parameters in SQL Statement
  • .
  • Dim conn As New OleDbConnection()
  • Dim cmd As New OleDbCommand()
  • cmd.CommandText _
  • "UPDATE ACTIVITY SET MEETINGID ?, NAME ?,
    DESCRIPTION ?," _
  • " DATEBEGIN ?, DATEEND ? WHERE (ID
    ?)"
  • cmd.Parameters.Clear()
  • cmd.Parameters.Add("MeetingID",
    OleDbType.Integer).Value _
  • CType(Session("MeetingID"), Integer)
  • cmd.Parameters.Add("Name", OleDbType.VarChar).Valu
    e Name
  • cmd.Parameters.Add("Description",
    OleDbType.VarChar).Value Description
  • cmd.Parameters.Add("Datebegin",
    OleDbType.DBTimeStamp).Value DateBegin
  • cmd.Parameters.Add("DateEnd", OleDbType.DBTimeStam
    p).Value DateEnd
  • cmd.Parameters.Add("ID", OleDbType.Integer).Value
    key
  • .

79
Revised version of InsertProduct.aspx (partial
code)
  • Try
  • OleDbInsertCommand1.CommandText _
  • " INSERT INTO Products(ProductName,
    CategoryID, UnitPrice, Discontinued) " _
  • " VALUES (?, ?, ?, ?) "
  • OleDbInsertCommand1.Parameters.Clear()
  • OleDbInsertCommand1.Parameters.Add("ProductN
    ame", OleDbType.VarChar).Value _
  • TextBoxProductName.Text
  • OleDbInsertCommand1.Parameters.Add("Category
    ID", OleDbType.Integer).Value
    TextBoxCategoryID.Text
  • OleDbInsertCommand1.Parameters.Add("UnitPric
    e", OleDbType.Decimal).Value TextBoxUnitPrice.Te
    xt
  • OleDbInsertCommand1.Parameters.Add("Disconti
    nued", OleDbType.Boolean).Value
    CheckBoxDiscontinued.Checked
  • OleDbConnection1.ConnectionString _
  • "ProviderMicrosoft.Jet.OLEDB.4.0Pa
    ssword''User IDAdmin" _
  • "Data Source"
    Server.MapPath("Northwind.mdb")
  • ..

80
Create a Parameterized SQL
  • A parameterized query for a SQL Server command
  • Select ProductID, Name, ShortDescription, OnHand,
    UnitPrice
  • From Products
  • Where ProductID _at_ProductID
  • A parameterized query for an OLE DB or ODBC
    command
  • Select ProductID, Name, ShortDescription, OnHand,
    UnitPrice
  • From Products
  • Where ProductID ?
  • A parameterized query for an Oracle command
  • Select ProductID, Name, ShortDescription, OnHand,
    UnitPrice
  • From Products
  • Where ProductID ProductID

81
Change from OleDB to SQL Server
  • lt_at_ Import Namespace"System.Data.OleDB" gt
  • lt_at_ Import Namespace"System.Data.SqlClient" gt
  • Imports System.Data.OleDB
  • Imports System.Data.SqlClient
  • Dim cmd as New OleDbConnection()
  • Dim cmd as New SqlConnection()
  • Dim cmd as New OleDbCommand()
  • Dim cmd as New SqlCommand()
  • Dim dr as New OleDbDataReader()
  • Dim dr as New SqlDataReader()

In .aspx page
In code behind
82
New Features in ASP.NET 2.0
  • New Server Controls
  • Data Controls
  • Navigation Controls
  • Login Controls.
  • Web Part Controls
  • Master Pages
  • Themes and Skins
  • Personalization
  • Localization (Internationalization)

Source http//www.asp.net/QuickStart/aspnet/doc/w
hatsnew.aspx
83
Building Data-Driven Web Sites in ASP.NET 2.0

84
Codeless Data-Binding Process
Source http//beta.asp.net/QUICKSTART/aspnet/doc/
ctrlref/data/default.aspx
85
Data Bound Controls
  • DataGrid (superseded by the GridView)
  • DataList
  • GridView
  • DetailsView
  • FormView (template-based)
  • Repeater

New in ASP.NET 2.0
Declarative Data Sources
86
Create a New Data Source
  • Drag and drop the AccessDataSource Web server
    control on to a Web form.
  • Click the smart tab of the AccessDataSource1 to
    select common tasks for the AccessDataSource
  • Click on the Configure Data Source task

Smart tag icon
Smart tag menu
87
Select the Access database
88
Define a SQL (Select) statement
Don't choose any query name IF you need to create
a data source that will be used to insert,
update, or delete data in the database.
  • SELECT CategoryID, CategoryName,
    Description FROM Categories

89
ltaspAccessDataSourcegt Web Server Control
  • ltaspAccessDataSource ID"AccessDataSource1"
    runat"server" DataFile"/App_Data/northwind.mdb"
  • SelectCommand"SELECT CategoryID,
    CategoryName, Description FROM Categories"gt
  • lt/aspAccessDataSourcegt

90
CategoryList.aspx
91
Connecting Data Source and GridView
  • Drop and drop a GridView to the Web form
  • From the GridView smart tag menu, click on the
    dropdown listbox -- Choose Data Source and then
    select AccessDataSource1

92
Edit Columns
93
Edit Columns
94
Create a HyperLinkField for the CategoryName
Column
  • Delete the CategoryName from the Selected Fields
    list box
  • Highlight HyperlinkField and click Add
  • Move the HyperLinkField to the position between
    CategoryID and Description in the Selected Fields
    list box
  • Set up the properties of the HyperlinkField

95
Set up HyperlinkField
  • Set up the Hyperlink field so that it displays
    CategoryName as the link words, and links to
    ProductsByCategory.aspx while passing two
    QueryString variables cid and cname where cid
    contains CategoryID and cname contains
    CategoryName

CategoryID CategoryName
CategoryID, CategoryName
ProductsByCategory.aspx?cid0cname1
96
Source Code
  • ltaspGridView ID"GridView1" runat"server"
    AutoGenerateColumns"False" DataKeyNames"Category
    ID"
  • DataSourceID"AccessDataSource1"gt
  • ltColumnsgt
  • ltaspBoundField
    DataField"CategoryID"
  • HeaderText"CategoryID" InsertVisible"False"
  • ReadOnly"True"
    SortExpression"CategoryID" /gt
  • ltaspHyperLinkField
  • DataNavigateUrlFields"CategoryID,
    CategoryName"
    DataNavigateUrlFormatString
  • "ProductsByCategory.aspx?cid0ampcname1"
  • DataTextField"CategoryNam
    e"
  • HeaderText"Category
    Name" /gt
  • ltaspBoundField
    DataField"Description" H
  • HeaderText"Description" SortExpression"Descr
    iption" /gt
  • lt/Columnsgt
  • lt/aspGridViewgt

97
CategoryList.aspx
  • lt_at_ Page Language"VB" gt
  • lt!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http//www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"gt
  • ltscript runat"server"gt
  • lt/scriptgt
  • lthtml xmlns"http//www.w3.org/1999/xhtml" gt
  • lthead runat"server"gt
  • lttitlegtUntitled Pagelt/titlegt
  • lt/headgt
  • ltbodygt
  • ltform id"form1" runat"server"gt
  • ltdivgt
  • lth1gt
  • Category Listlt/h1gt
  • ltpgt
  • ltaspGridView ID"GridView1"
    runat"server" AutoGenerateColumns"False"
    DataKeyNames"CategoryID"
  • DataSourceID"AccessDataSource1"gt
  • ltColumnsgt
  • ltaspBoundField
    DataField"CategoryID" HeaderText"CategoryID"
    InsertVisible"False"
  • ReadOnly"True"
    SortExpression"CategoryID" /gt

98
ProductsByCategory.aspx
99
Design the User Interface
  • Choose Data Source
  • Edit Data Source

100
Define the SQL Statement
Make sure you choose Products table
SELECT ProductID, ProductName,
Discontinued, UnitPrice FROM Products WHERE
(CategoryID ? )
101
Add Where Clause
102
Parameter Types
Name
Description
Parameter
Binds a replaceable parameter to a data field
ControlParameter
Binds a replaceable parameter to a control
property
CookieParameter
Binds a replaceable parameter to a cookie value
FormParameter
Binds a replaceable parameter to a form field
ProfileParameter
Binds a replaceable parameter to a profile
property
QueryStringParameter
Binds a replaceable parameter to a query string
parameter
SessionParameter
Binds a replaceable parameter to a session
variable
103
(No Transcript)
104
TemplateField
105
Code for TemplateField
  • ltaspTemplateField HeaderText"ProductName"
    SortExpression"ProductName"gt
  • ltItemTemplategt
  • ltaspLabel ID"Label1" runat"server"
    Text'lt Bind("ProductName") gt'gtlt/aspLabelgt
  • lt/ItemTemplategt
  • ltEditItemTemplategt
  • ltaspTextBox ID"TextBox1"
    runat"server" Text'lt Bind("ProductName")
    gt'gtlt/aspTextBoxgt
  • lt/EditItemTemplategt
  • lt/aspTemplateFieldgt

106
Edit Template
107
Edit Template
108
Set Up Text property
109
Set up NavigateUrl property
  • ProductRecord.aspx?pid0

110
End Template Editing
111
ProductsByCategory.aspx
lt_at_ Page Language"VB" gt lt!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.1//EN" "http//www.w3.org/TR/
xhtml11/DTD/xhtml11.dtd"gt ltscript
runat"server"gt Protected Sub Page_Load(ByVal
sender As Object, ByVal e As System.EventArgs)
LabelCategoryID.Text Request.QueryString("c
id") LabelCategoryName.Text
Request.QueryString("cname") End
Sub lt/scriptgt lthtml xmlns"http//www.w3.org/1999/
xhtml" gt lthead runat"server"gt
lttitlegtProducts by a Categorylt/titlegt lt/headgt ltbod
ygt ltform id"form1" runat"server"gt
ltdivgt ltstronggtCategoryID lt/stronggt
ltaspLabel ID"LabelCategoryID"
runat"server"gtlt/aspLabelgtltstronggtnbsp
Catgeory Name lt/stronggt
ltaspLabel ID"LabelCategoryName"
runat"server"gtlt/aspLabelgtltbr /gt ltbr /gt

112
Continued
ltaspGridView ID"GridView1" runat"server"
AutoGenerateColumns"False" DataKeyNames"Product
ID" DataSourceID"AccessDataSource1"
BackColor"White" BorderColor"CC9966"
BorderStyle"None" BorderWidth"1px"
CellPadding"4" gt ltColumnsgt ltaspBoundField
DataField"ProductID" HeaderText"Product ID"
InsertVisible"False"
ReadOnly"True" SortExpression"ProductID" /gt
ltaspTemplateField HeaderText"Product Name"
SortExpression"ProductName"gt
ltItemTemplategt ltaspHyperLink
ID"HyperLink1" runat"server"
NavigateUrl'lt Eval("ProductID",
"ProductRecord.aspx?pid0") gt'
Text'lt Eval("ProductName") gt'gtlt/aspHyperLinkgt
lt/ItemTemplategt ltEditItemTemplategt
ltaspTextBox ID"TextBox1" runat"server"
Text'lt Bind("ProductName")
gt'gtlt/aspTextBoxgt lt/EditItemTemplategt lt/asp
TemplateFieldgt
113
Continued
  • ltaspCheckBoxField DataField"Discontinued"
  • HeaderText"Discontinued"
  • SortExpression"Discontinued" /gt
  • ltaspBoundField DataField"UnitPrice"
  • HeaderText"Unit Price"
  • SortExpression"UnitPrice"
  • DataFormatString"0c" HtmlEncode"false"
    gt
  • ltItemStyle HorizontalAlign"Ri
    ght" /gt
  • lt/aspBoundFieldgt
  • lt/Columnsgt
  • ltFooterStyle BackColor"FFFFCC"
    ForeColor"330099" /gt
  • ltRowStyle BackColor"White" ForeColor"330099"
    /gt
  • ltPagerStyle BackColor"FFFFCC"
    ForeColor"330099"
  • HorizontalAlign"Center" /gt
  • ltSelectedRowStyle BackColor"FFCC66"
    Font-Bold"True"
  • ForeColor"663399" /gt
  • ltHeaderStyle BackColor"990000" Font-Bold"True"
  • ForeColor"FFFFCC" /gt
  • lt/aspGridViewgt

114
Continued
ltaspAccessDataSource ID"AccessDataSource1"
runat"server" DataFile"/App_Data/northwin
d.mdb" SelectCommand"SELECT ProductID,
ProductName, Discontinued,
UnitPrice FROM Products WHERE
(CategoryID ?)"gt
ltSelectParametersgt
ltaspQueryStringParameter DefaultValue"1"
Name"CategoryID" QueryStringField"cid"
Type"Int32" /gt
lt/SelectParametersgt lt/aspAccessDataSource
gt lt/divgt lt/formgt lt/bodygt lt/htmlgt
115
ProductRecord.aspx Runtime
116
Use DetailsView (One Record at a Time)
117
Define the SQL Statement
  • SELECT ProductID, ProductName, CategoryID,
    UnitPrice, UnitsInStock, Discontinued FROM
    Products WHERE (ProductID ?)

118
Add Where Clause
119
Format the DetailsView
120
ProductRecord.aspx
  • lt_at_ Page Language"VB" gt
  • lt!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http//www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"gt
  • ltscript runat"server"gt
  • lt/scriptgt
  • lthtml xmlns"http//www.w3.org/1999/xhtml" gt
  • lthead runat"server"gt
  • lttitlegtUntitled Pagelt/titlegt
  • lt/headgt
  • ltbodygt
  • ltform id"form1" runat"server"gt
  • ltdivgt
  • lth1gtProduct Recordlt/h1gt
  • ltaspDetailsView ID"DetailsView1"
    runat"server" AutoGenerateRows"False"
    CellPadding"4"
  • DataKeyNames"ProductID"
    DataSourceID"AccessDataSource1"
  • Font-Bold"False" ForeColor"333333"
    GridLines"None" Height"50px"gt
  • ltFooterStyle BackColor"507CD1"
    Font-Bold"True" ForeColor"White" /gt
  • ltCommandRowStyle BackColor"D1DDF1"
    Font-Bold"True" /gt
  • ltRowStyle BackColor"EFF3FB" /gt
  • ltFieldHeaderStyle BackColor"DEE8F5"
    Font-Bold"True" /gt

121
Continued
  • ltaspBoundField DataField"UnitPrice"
    DataFormatString"0c"
  • HeaderText"UnitPrice"
  • SortExpression"UnitPrice"gt
  • lt/aspBoundFieldgt
  • ltaspBoundField
    DataField"UnitsInStock" DataFormatString"0 in
    stock"
  • HeaderText"UnitsInStock"
  • SortExpression"UnitsInStock"
    /gt
  • ltaspCheckBoxField
    DataField"Discontinued" HeaderText"Discontinued"
  • SortExpression"Discontinued" /gt
  • lt/Fieldsgt
  • ltHeaderStyle BackColor"507CD1"
    Font-Bold"True" ForeColor"White" /gt
  • ltEditRowStyle BackColor"2461BF"
    /gt
  • ltAlternatingRowStyle
    BackColor"White" /gt
  • lt/aspDetailsViewgt
  • ltaspAccessDataSource ID"AccessDataSource
    1" runat"server"
  • DataFile"/App_Data/northwind.mdb"
  • SelectCommand"SELECT ProductID,
    ProductName, CategoryID, UnitPrice,
  • UnitsInStock, Discontinued FROM Products
    WHERE (ProductID ?)"gt
  • ltSelectParametersgt

122
CategoryProductMasterDetail.aspx
123
CategoryProductMasterDetail.aspx
  • lt_at_ Page Language"VB" gt
  • lt!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http//www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"gt
  • ltscript runat"server"gt
  • Protected Sub DropDownList1_SelectedIndexChang
    ed(ByVal sender As Object, ByVal e As
    System.EventArgs)
  • LabelCategory.Text "Category ID
    selected " DropDownList1.SelectedItem.Value
  • LabelCategory.Text "ltbrgtCategory Name
    selected " DropDownList1.SelectedItem.Text
  • End Sub
  • lt/scriptgt
  • lthtml xmlns"http//www.w3.org/1999/xhtml" gt
  • lthead runat"server"gt
  • lttitlegtUntitled Pagelt/titlegt
  • lt/headgt
  • ltbodygt
  • ltform id"form1" runat"server"gt
  • ltdivgt
  • ltaspDropDownList ID"DropDownList1"
    runat"server" AutoPostBack"True"
  • DataSourceID"AccessDataSource1"
  • DataTextField"CategoryName"
    DataValueField"CategoryID"
  • OnSelectedIndexChanged"DropDownList1_SelectedIn
    dexChanged"gt

124
CategoryProductMasterDetail3.aspx
125
CatgeoryProductMasterDetail2.aspx
126
CategoryProductMasterDetail3.aspx
  • lt_at_ Page Language"VB" gt
  • lt!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http//www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"gt
  • ltscript runat"server"gt
  • Protected Sub DropDownList1_SelectedIndexChanged(B
    yVal sender As _
  • Object, ByVal e As System.EventArgs)
  • If DropDownLis1.SelectedValue "" Then
  • LabelCategory.Text "Please select a
    category! "
  • Else
  • LabelCategory.Text "Category ID
    selected " _
  • DropDownList1.SelectedItem.Value
  • LabelCategory.Text "ltbrgtCategory Name
    selected " _
  • DropDownList1.SelectedItem.Text
  • End Sub
  • lt/scriptgt

127
Continued
  • lthtml xmlns"http//www.w3.org/1999/xhtml" gt
    lthead runat"server"gt
  • lttitlegtUntitled Pagelt/titlegt
  • lt/headgt
  • ltbodygt
  • ltform id"form1" runat"server"gt
  • ltdivgt
  • ltaspDropDownList ID"DropDownList1"
    runat"server"
  • AutoPostBack"True" DataSourceID"AccessDataSour
    ce1"
  • DataTextField"CategoryName"
    DataValueField"CategoryID"
  • AppendDataBoundItemstruegt
  • ltaspListItem Text"-- Choose a category --"
    Value"" /gt
  • lt/aspDropDownListgt
  • ltaspAccessDataSource ID"AccessDataSource
    1" runat"server"
  • DataFile"/App_Data/northwind.mdb"
  • SelectCommand"SELECT CategoryID,
    CategoryName FROM
  • Categories"
  • CancelSelectOnNullParameterfalsegt
  • lt/aspAccessDataSourcegt
  • ltbr /gt

128
Continued
  • ltaspGridView ID"GridView1" runat"server"
    AutoGenerateColumns"False"
  • DataKeyNames"ProductID"
    DataSourceID"AccessDataSource2"gt
  • ltColumnsgt
  • ltaspBoundField
    DataField"ProductID" HeaderText"ProductID"
  • InsertVisible"False" ReadOnly"True"
    /gt
  • ltaspBoundField
    DataField"ProductName" HeaderText"ProductName"
    /gt
  • ltaspBoundField
    DataField"SupplierID" HeaderText"SupplierID" /gt
  • ltaspBoundField
    DataField"UnitPrice" HeaderText"UnitPrice" /gt
  • ltaspBoundField
    DataField"UnitsInStock" HeaderText"UnitsInStock"
    /gt
  • ltaspCheckBoxField
    DataField"Discontinued" HeaderText"Discontinued"
    /gt
  • lt/Columnsgt
  • lt/aspGridViewgt
  • ltaspAccessDataSource ID"AccessDataSource
    2" runat"server"
  • DataFile"/App_Data/northwind.mdb"
  • SelectCommand"SELECT ProductID,
    ProductName, SupplierID, UnitPrice,
  • UnitsInStock, Discontinued FROM Products
    WHERE (CategoryID ?)"gt
  • ltSelectParametersgt
  • ltaspControlParameter
    ControlID"DropDownList1" Name"CategoryID"
  • PropertyName"SelectedValue" Type"Int32" /gt

129
2
1
130
(No Transcript)
131
(No Transcript)
132
Manage Categories
133
Design View
134
Define the SQL Statement
135
Use Optimistic Concurrency Control
ltaspAccessDataSource ID"AccessDataSource1"
runat"server" DataFile"/App_Data/no
rthwind.mdb" DeleteCommand"DELETE FROM
Categories WHERE CategoryID ? AND
CategoryName ? AND Description ?"
InsertCommand"INSERT INTO Categories
(CategoryID, CategoryName, Description)
VALUES (?, ?, ?)" SelectCommand"SELEC
T CategoryID, CategoryName, Description
FROM Categories"
UpdateCommand"UPDATE Categories SET
CategoryName ?, Description ? WHERE
CategoryID ? AND CategoryName ? AND
Description ?" ConflictDetection"CompareAllV
alues"gt ltDeleteParametersgt
ltaspParameter Name"original_CategoryID"
Type"Int32" /gt ltaspParameter
Name"original_CategoryName" Type"String" /gt
ltaspParameter Name"original_Descript
ion" Type"String" /gt
lt/DeleteParametersgt
ltUpdateParametersgt ltaspParameter
Name"CategoryName" Type"String" /gt
ltaspParameter Name"Description"
Type"String" /gt ltaspParameter
Name"original_CategoryID" Type"Int32" /gt
ltaspParameter Name"original_CategoryNam
e" Type"String" /gt
ltaspParameter Name"original_Description"
Type"String" /gt lt/UpdateParametersgt
ltInsertParametersgt
ltaspParameter Name"CategoryID" Type"Int32" /gt
ltaspParameter Name"CategoryName"
Type"String" /gt ltaspParameter
Name"Description" Type"String" /gt
lt/InsertParametersgt lt/aspAccessDataSource
gt
136
Without Optimistic Concurrency Control
ltaspAccessDataSource ID"AccessDataSource1"
runat"server" DataFile"/App_Data/no
rthwind.mdb" DeleteCommand"DELETE FROM
Categories WHERE CategoryID ?"
InsertCommand"INSERT INTO Categories
(CategoryID, CategoryName, Description)
VALUES (?, ?, ?)" SelectCommand"SELEC
T CategoryID, CategoryName, Description
FROM Categories"
UpdateCommand"UPDATE Categories SET
CategoryName ?, Description ? WHERE
CategoryID ?"gt ltDeleteParametersgt
ltaspParameter Name"original_Cate
goryID" Type"Int32" /gt
lt/DeleteParametersgt
ltUpdateParametersgt ltaspParameter
Name"CategoryName" Type"String" /gt
ltaspParameter Name"Description"
Type"String" /gt ltaspParameter
Name"original_CategoryID" Type"Int32" /gt
lt/UpdateParametersgt
ltInsertParametersgt ltaspParameter
Name"CategoryID" Type"Int32" /gt
Write a Comment
User Comments (0)
About PowerShow.com