ASP.NET and ADO.NET - PowerPoint PPT Presentation

1 / 84
About This Presentation
Title:

ASP.NET and ADO.NET

Description:

Just drag and drop to create controls. Server Explorer for database & server object creations ... Create a new data connection from the Server Explorer ... – PowerPoint PPT presentation

Number of Views:1048
Avg rating:3.0/5.0
Slides: 85
Provided by: min91
Category:
Tags: ado | asp | net | creations | rightmouse

less

Transcript and Presenter's Notes

Title: ASP.NET and ADO.NET


1
  • ASP.NET and ADO.NET
  • Minder Chen, Ph.D.
  • Associate Professor of
  • Decision Sciences and MIS
  • School of Management
  • George Mason University
  • Fairfax, VA 22030
  • Email mchen_at_gmu.edu
  • 703-993-1788

ASP ? ASP.NET ADO ? ADO.NET VB ? VB.NET Java
? C (J)
2
Outline
  • Introduction to ASP.NET in the Context of .NET
    Framework
  • Web Programming ASP.NET
  • Web server control and Event-Driven programming
  • Postback and ViewState
  • Code-behind
  • Database Programming ADO.NET
  • DataReader
  • DataSet and DataGrid
  • Topics to be covered in ASP.NET
  • Curriculum Design Where does ASP.NET and ADO.NET
    fit in?
  • References Online resources and books

3
ASP.NET in the Context of .NET Framework
VB
C
C
JScript
J
Visual Studio.NET
Common Language Specification
ASP.NET Web Forms Web Services Mobile Internet
Toolkit
Windows Forms
ADO.NET and XML
Base Class Library
Common Language Runtime
Operating System
4
Web Programming with ASP.NET
  • Attractive features in ASP.NET
  • Setup ASP.NET Environments
  • Web Forms
  • Postback and ViewState
  • Code-Behind
  • ASP.NET Execution Models
  • Web Form Controls
  • HTML Controls (form elements)
  • HTML Server Controls
  • Web Server Controls
  • User Controls

5
ASP.NET Features
  • Event-driven programming
  • HTML Server Controls or Web Server Controls
  • Postback and ViewState
  • Separation of user interface (UI) and code
  • Code-behind
  • Scalability
  • Cache object
  • Server-farm support
  • Page Caching
  • State maintenance
  • ViewState, Cookie, Session, Application, Cache
  • Cookie-less session support
  • Visual Studio .NET development tool
  • Just drag and drop to create controls
  • Server Explorer for database server object
    creations

6
Setting Up the Development Environment
  • Visual Studio .NET Windows XP Professional,
    Windows NT, Windows 2000 with IIS installed
    first.
  • ASP.NET Web Matrix
  • ASP.NET Web Matrix is supported on Windows 2000
    (Professional and Server editions) and Windows XP
    (Home, Professional) operating systems. 
  • You must have IE 5.5 or greater and the .NET
    Framework installed.
  • Can be downloaded for free from
    http//www.asp.net/webmatrix/
  • Set up your own Internet Information Server (IIS)
    on a Windows NT Server or 2000 Server
  • Install IIS with WWW Service and FTP service
  • Set up ftp accounts for students
  • Install .NET Framework SDK
  • Use Web Hosting Providers Supporting ASP.NET,
    such as Brinkster.com (free)

7
Hello1.asp (First Generation Technology)
  • lthtmlgtltbodygt
  • lth1gtHello Old ASP!lt/h1gt
  • Current Time
  • lt
  • Response.Write(Now())
  • gt
  • ltformgt
  • Enter your name ltinput type"text"
    name"userName"gt
  • ltinput type"Submit" value"Enter"gt
  • lt/formgtlt/bodygtlt/htmlgt
  • The limitation of classic ASP is that the render
    block has to be placed where you want the output
    to appear. It is impossible to separate
    executable code from the HTML code itself. This
    makes the web page difficult to understand and
    difficult to maintain.
  • A form without an action attribute submits form
    data to itself and the form will be refreshed to
    its default status.

8
Hello3.aspx
9
ASP.NET Web Form Composition
Compiler Directive
  • lt_at_ Page language"VB" gt
  • lthtmlgt
  • ltheadgt
  • lt-- Script block --gt
  • ltscript language"VB" runat"server"gt
  • Private x as String "Developed by Minder
    Chen"
  • Sub Page_Load(Src As Object, e As
    EventArgs)
  • If Name.Text "" Then
  • Message.Text ""
  • Else
  • Message.Text "Hi " Name.Text
  • End If
  • End Sub
  • Sub Show_Author(Src As Object, e As
    EventArgs)
  • DataBind( ) ' Bind data binding
    expressions
  • End Sub
  • lt/scriptgt
  • lt/headgt

HTML tags
Server-Side Comment
Code Block
10
Continued
Output Directive Render Block
Static Text
  • ltbodygt
  • Current time lt Date.Now() gt
  • ltform runat"server" ID"Form1"gt
  • Enter your name
  • ltasptextbox id"Name" runat"server" /gt
  • ltinput type"submit" value"Enter your
    name"gtltpgt
  • ltasplabel id"Message" runat"server" /gtltbrgt
  • ltinput type"button"
  • OnServerClick "Show_author"
  • value"Who is the author?"
  • runat"server"gt ltbrgt
  • ltbgt lt "Message" x gt
  • lt/bgtlt/formgtlt/bodygtlt/htmlgt

Server Control Tags
Server-side event procedure
Data Binding Expression
11
Add New Project Items
  • Choose Web Form
  • Enter Hello.aspx as item name

12
pageLayout property
  • FlowLayout
  • GridLayout

13
pageLayout
  • pageLayout
  • FlowLayout
  • GridLayout

14
Hello.aspx
  • lthtmlgt
  • ltscript language"VB" runat"server"gt
  • Sub EnterBtn_Click(Src As Object, e As
    EventArgs)
  • Message.Text "Hi " Name.Text ",
    welcome to ASP.NET!"
  • End Sub
  • lt/scriptgt
  • ltbodygt
  • ltform runat"server"gt
  • Enter your name ltasptextbox id"Name"
    runatserver/gt
  • ltaspbutton text"Enter" OnClick"EnterBtn_Cli
    ck" runat"server" /gt
  • ltpgt
  • ltasplabel id"Message" runatserver/gt
  • lt/formgt
  • lt/bodygt
  • lt/htmlgt

Design time
Run time
15
Web Server Controls
  • lthtmlgt
  • ltscript language"VB" runat"server"gt
  • Sub EnterBtn_Click(Src As Object, e As
    EventArgs)
  • Message.Text "Hi " Name.Text _
  • ", welcome to ASP.NET!"
  • End Sub
  • lt/scriptgt
  • ltbodygt
  • ltform runat"server"gt
  • Enter your name
  • ltasptextbox id"Name"
  • runatserver/gt
  • ltaspbutton text"Enter"
  • OnClick"EnterBtn_Click" runat"server"/gt
  • ltasplabel id"Message" runatserver/gt
  • lt/formgtlt/bodygtlt/htmlgt

Use id attribute to assign an unique identifier
to each control in order to refer to it in your
program.
16
Design vs. HTML Mode
17
Run and Test Your ASP.NET Program
  • Right mouse click the Hello.aspx at Solution
    Explorer
  • Choose Set as Start Page
  • Choose Start to run the program.
  • After testing the generated page in the browser.
    Close the browser to go back to the editing mode.

You need to close the browser in order to modify
your code again!
18
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.

?
single file
separate files (code-behind)
code
code
lttagsgt
lttagsgt
Form1.aspx
Form1.aspx
Form1.aspx.vb
19
Hello2.aspx Runtime
Minder
20
Design View and HTML View
21
Code Behind
22
Events Handlers in Hello2.aspx.vb (Code Behind)
  • Private Sub Page_Load(ByVal sender As
    System.Object, _
  • ByVal e As System.EventArgs) Handles
    MyBase.Load
  • ' Put user code to initialize the page
    here
  • If Not Page.IsPostBack Then
  • Label1.Text "First Time "
  • Else
  • Label1.Text "Post back "
  • End If
  • Label1.Text "ltbrgtLoad event of Page"
  • End Sub
  • Private Sub Button1_Click(ByVal sender As
    System.Object, _
  • ByVal e As System.EventArgs) Handles
    Button1.Click
  • LabelName.Text "Hello "
    TextBox1.Text "!"
  • Label1.Text "ltbrgtClick event of
    Button1"
  • End Sub
  • Private Sub TextBox1_TextChanged(ByVal sender
    As System.Object, _
  • ByVal e As System.EventArgs) Handles
    TextBox1.TextChanged
  • Label1.Text "ltbrgtTextChanged event
    of TextBox1"
  • End Sub

23
Page/Control Event Execution
PostBack
First Request
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
Page_PreRender
Control hierarchy (Dynamically generated HTML
page) is rendered
Page_Unload
Page is disposed
24
ViewState and PostBack
Hello2.aspx.vb If Not IsPostBack Then
Label1.Text"First Time" Else Label1.Text"Post
Back" End If
Hello2.aspx
ltasptextbox id"TextBox1" runat"server"/gt ltaspb
utton id"Button1" runat"server" /gt
Minder Chen
States of a page is maintained via the ViewState
between the Postback
25
ASP.NET Execution Model
Class Hello Private Sub Page_Load() End Sub
End Class Hello.aspx.vb
Client Server
First request
Postback
Output Cache
26
State Management
  • HTTP protocol and Web Forms pages are stateless.
  • Pages are destroyed and recreated with each round
    trip to the server.
  • State management is to maintain state and page
    information over multiple requests for the same
    or different pages
  • State Management Mechanism
  • QueryString (hyperlink or form data via Get
    method)
  • Form elements including hidden field (Post
    method)
  • Cookie (per client machine and last longer)
  • Session (for each visitor during a visit)
    Support Cookie-less Sessions
  • Application (per Web application)
  • ViewState (Postback of the same page )
  • Cache (Per Web application)

27
ADO.NET
  • ADO.NET Object Model
  • Using ADO.NET with ASP.NET
  • DataReader
  • DataSet and DataGrid A Powerful Combination
  • Browsing
  • Sorting
  • Filtering
  • Selection
  • Pagination
  • In-place Editing (Data Maintenance)

28
ADO.NET Object Model
ADO.Net
Data Consumers
Data Provider 2
Window Forms
Data Provider 1 (Managed Component)
DataSet
DataAdapter
Web Forms
Connection
Command
SQL statement (Insert, Update, Delete)
SQL Select Statement
Web Services Mobile Forms Classes Console App.
DataReader
Records
29
Data Objects
30
DataReader Direct Access to Database
  • Select
  • Stored procedure

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

Web Form
Database
31
Cursor of a "Record Set"
Dim dr As OleDbDataReader dr
catCMD.ExecuteReader()
Column index
0 1 2
Num Name Price
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.
Record set
By Zero-based Column Cardinal By Column Name 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
dr.getDecimal("Price") is illegal!
32
Connection String
  • Create a new data connection from the Server
    Explorer
  • Drag the newly created Data Connection onto a web
    form to create a connection. An icon of the
    connection will be displayed under the form.
  • Select this connection icon. Double click on
    Connection String Property to select the actual
    connection string's value. Copy it and paste it
    to your program.

33
Data Link Properties
34
CategoryList.aspx
35
CategoryList.aspx.vb
  • Imports System.Data.OleDb
  • Public Class CategoryList
  • Inherits System.Web.UI.Page
  • Protected WithEvents Button1 As
    System.Web.UI.WebControls.Button
  • Protected WithEvents Label1 As
    System.Web.UI.WebControls.Label
  • Protected WithEvents Label2 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
  • If Not IsPostBack Then
  • Dim conn As OleDbConnection
  • Dim cmd As OleDbCommand
  • Dim dr As OleDbDataReader

36
Continued
  • Try
  • conn New _
  • OleDbConnection("PROVIDERMicrosoft.Jet.O
    LEDB.4.0" _
  • "Data Source" Server.MapPath("Northw
    ind.mdb"))
  • 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
  • dr.Close()
  • conn.Close()
  • End Try

Format the dynamically generated HTML page
37
DataSet
  • Containers for data know nothing about getting
    data from database
  • Disconnected and in-memory cache of
    database or XML data.
  • Mobile applications using smart devices such as
    Pocket PCs
  • Trade-off between performance and memory
    resources usage.
  • Dataset is full integrated with XML Data.

38
ADO.NET and ASP.NET
.ASPX Page
DataReader
Command
Database
Connection
DataAdapter
.ASPX Page
DataTable
DataSet
Data-Bound Control
DataView
39
Data Access with ADO.NET and DataGrid
SqlDataAdapter1.Fill(dsCategory1)
DataGrid1.DataBind()
Web Form (.ASPX)
Dataset
Database



Connection
Data Adapter






DataGrid1
SqlDataAdapter1.Update(dsCategory1)
40
Using ADO.NET and DataGrid Coding It Manually
41
CategoryManual.aspx
  • lt_at_ Import namespace"System.Data.OleDb" gt
  • lt_at_ Import namespace"System.Data" gt
  • lt_at_ Page Language"vb" gt
  • ltHTMLgtltHEADgtlttitlegtCategoryManuallt/titlegt
  • ltscript runat"server"gt
  • Sub Page_Load( ByVal sender As System.Object,
    ByVal e As System.EventArgs)
  • Dim conn As OleDbConnection
  • conn New _
  • OleDbConnection("PROVIDERMicrosoft.Jet.
    OLEDB.4.0" _
  • "Data Source" Server.MapPath("North
    wind.mdb") )
  • Dim ds As DataSet New DataSet()
  • Dim da As OleDbDataAdapter New _
  • OleDbDataAdapter("select from
    Categories", conn)
  • da.Fill(ds, "Categories")

Construct a new DataAdapter da based on the
SelectCommand against the Connection conn
Fill a DataTable "Categories" in the DataSet ds
using the DataAdapter da
42
Continued
  • ' Use a DataView as a DataSource
  • Dim dv as New DataView()
  • dv ds.Tables("Categories").DefaultView
  • DataGrid1.DataSource dv
  • DataGrid1.DataBind()
  • End Sub
  • lt/scriptgt
  • lt/HEADgt
  • ltbodygtltH1gtCategory Listlt/H1gt
  • ltform id"Form1" method"post" runat"server"gt
  • ltaspDataGrid id"DataGrid1"
    runat"server"gtlt/aspDataGridgt
  • lt/formgtlt/bodygtlt/HTMLgt

No need to open and close the Connection
associated with a DataAdapter.
  • Set DataMember property to a DataTable when the
    DataSource is a DataSet
  • DataGrid1.DataSource ds
  • DataGrid1.DataMember "Categories"
  • DataGrid1.DataBind()

43
Formatting, Paging, and Sorting
44
Create ProductSort.aspx
45
Create Connection and DataAdapter from a Table or
View
  • Drag and drop a database table from the Server
    Explorer to the web form!

Drag and drop
46
Configure Data Adapter
47
Create a Dataset DsProduct
48
Create and Set Up a DataGrid Control
49
(No Transcript)
50
Page_Load Event
  • Private Sub Page_Load(ByVal sender As
    System.Object, _
  • ByVal e As System.EventArgs) Handles MyBase.Load
  • ' DataGrid1 View State can retain data during
    PostBack
  • If Not IsPostBack Then
  • OleDbDataAdapter1.Fill(DsProduct1)
  • DataGrid1.DataBind()
  • End If
  • End Sub

51
Testing
52
Sorting
53
Set Sort Expression
Deselect this!
54
ProductSort.aspx
  • lt_at_ Page Language"vb" AutoEventWireup"false"
  • Codebehind"ProductSort.aspx.vb"
    Inherits"adogrid.ProductSort"gt
  • ltHTMLgt
  • ltHEADgtlttitlegtProductSortlt/titlegtlt/HEADgt
  • ltbodygtltH2gtProduct Listinglt/H2gtltPgt
  • ltform id"Form1" method"post" runat"server"gt
  • ltaspDataGrid idDataGrid1 runat"server"
    Width"285px" Height"248px"
  • DataSource"lt DsProduct1 gt"
    DataKeyField"ProductID" AllowSorting"True"
  • DataMember"Products" ShowFooter"True"
    AutoGenerateColumns"False"gt
  • ltColumnsgt
  • ltaspBoundColumn DataField"ProductID"
    HeaderText"ProductID"gtlt/aspBoundColumngt
  • ltaspBoundColumn DataField"ProductName"
    HeaderText"ProductName"gtlt/aspBoundColumngt
  • ltaspBoundColumn DataField"CategoryID"
    HeaderText"CategoryID"gtlt/aspBoundColumngt
  • ltaspBoundColumn DataField"UnitPrice"
    HeaderText"UnitPrice"gtlt/aspBoundColumngt
  • ltaspBoundColumn DataField"UnitsInStock"
    HeaderText"UnitsInStock"gtlt/aspBoundColumngt
  • lt/Columnsgt
  • lt/aspDataGridgt lt/Pgt
  • lt/formgt
  • lt/bodygtlt/HTMLgt

55
Implement DataGrid1_SortCommand()
56
Code - Version 1
  • Private Sub DataGrid1_SortCommand(ByVal source
    As Object, _
  • ByVal e As System.Web.UI.WebControls.DataGridSort
    CommandEventArgs) _
  • Handles DataGrid1.SortCommand
  • OleDbDataAdapter1.SelectCommand.CommandText
    _
  • " ORDER BY " e.SortExpression()
  • OleDbDataAdapter1.Fill(DsProduct1)
  • DataGrid1.DataBind()
  • End Sub

57
Modify the DataGrid Tag in the .aspx Code
Critical Remove these attributes. You
don't need these when you use a Data View as a
data source!
  • From
  • ltaspdatagrid idDataGrid1 runat"server"
  • Width"464px" Height"284px"
  • DataSource"lt DsProduct1 gt"
  • DataKeyField"ProductID"
  • DataMember"Products"
  • AllowSorting"True" ShowFooter"True"
  • AutoGenerateColumns"False"gt
  • TO
  • ltaspdatagrid id"DataGrid1" runat"server"
  • Height"284px" Width"464px"
  • AutoGenerateColumns"False"
  • ShowFooter"True" AllowSorting"True" gt

58
Use Cache Object - Version 2
  • Private Sub Page_Load(ByVal sender As
    System.Object, _
  • ByVal e As System.EventArgs) Handles
    MyBase.Load
  • Dim dv As DataView
  • If Not IsPostBack Then
  • dv GetProductDV()
  • dv.Sort "" ' Default sorting order
  • DataGrid1.DataSource dv
  • DataGrid1.DataBind()
  • End If
  • End Sub

59
Store Product View in the Cache Object
  • Private Function GetProductDV() As DataView
  • Dim dvProduct As DataView
  • dvProduct Cache("ProductDV")
  • If dvProduct Is Nothing Then
  • OleDbDataAdapter1.Fill(DsProduct1)
  • dvProduct DsProduct1.Tables(0).DefaultVie
    w()
  • Cache("ProductDV") dvProduct
  • End If
  • Return dvProduct
  • End Function

Use Cache.remove("ProductDV") to remove
ProductDV from the Cache object when you add a
new product or update existing products in your
Products table.
60
Continued (Handle Sorting Event)
  • Private Sub DataGrid1_SortCommand(ByVal source As
    Object, _
  • ByVal e As System.Web.UI.WebControls.DataGridSort
    CommandEventArgs) _
  • Handles DataGrid1.SortCommand
  • Dim dv As DataView
  • dv GetProductDV()
  • Dim ordering As String
  • If Viewstate("direction") Is Nothing Then
  • ordering " ASC"
  • Else
  • If ViewState("direction") " ASC"
    Then
  • ordering " DESC"
  • Else
  • ordering " ASC"
  • End If
  • End If
  • ViewState("direction") ordering
  • dv.Sort e.SortExpression ordering
  • DataGrid1.DataSource dv
  • DataGrid1.DataBind()

Toggle sorting order between DESC or ASC using
ViewState object to store the previous sorting
order
61
Format UnitPrice
ltaspBoundColumn DataField"UnitPrice"
SortExpression"UnitPrice" HeaderText"UnitPrice
" DataFormatString"0C"gt ltItemStyle
HorizontalAlign"Right"gt lt/ItemStylegt lt/aspBo
undColumngt
62
Auto Format
63
Run-Time
64
Pagination Run-Time Result
Header
Item
Alternating Item
Footer (Hidden by default)
Page Bar
Page Link
65
Paging Properties
  • Click right mouse button.
  • Choose Property Builder

66
ProductPaging.aspx
  • lt_at_ Page Language"vb" AutoEventWireup"false"
  • Codebehind"ProductPaging.aspx.vb"
    Inherits"adogrid.ProductPaging"gt
  • ltHTMLgtltHEADgtlttitlegtProductSortlt/titlegtlt/HEADgt
  • ltbodygtltH2gtProduct Listingnbsp lt/H2gt
  • ltform id"Form1" method"post"
    runat"server"gtltPgt
  • ltaspdatagrid id"DataGrid1" runat"server"
  • Height"282px" Width"587px" AutoGenerateColumns
    "False"
  • ShowFooter"True" AllowSorting"True"
    BorderWidth"1px"
  • BorderColor"CC9966" BorderStyle"None"
    BackColor"White"
  • CellPadding"4" PageSize"5" AllowPaging"True"gt
  • ltSelectedItemStyle Font-Bold"True"
    ForeColor"663399"
  • BackColor"FFCC66"gtlt/SelectedItemStylegt
  • ltAlternatingItemStyle BackColor"Aqua"gtlt/Alternati
    ngItemStylegt
  • ltItemStyle ForeColor"330099" BackColor"White"gtlt
    /ItemStylegt
  • ltHeaderStyle Font-Bold"True" ForeColor"FFFFCC"
  • BackColor"990000"gtlt/HeaderStylegt
  • ltFooterStyle ForeColor"330099"
    BackColor"FFFFCC"gtlt/FooterStylegt

67
Continued
  • ltColumnsgt
  • ltaspBoundColumn DataField"ProductID"
  • SortExpression"ProductID" HeaderText"ProductID"
    gtlt/aspBoundColumngt
  • ltaspBoundColumn DataField"ProductName"
  • SortExpression"ProductName" HeaderText"ProductN
    ame"gt
  • ltHeaderStyle Width"200px"gt
    lt/HeaderStylegtlt/aspBoundColumngt
  • ltaspBoundColumn DataField"CategoryID"
  • SortExpression"CategoryID" HeaderText"CategoryI
    D"gtlt/aspBoundColumngt
  • ltaspBoundColumn DataField"UnitPrice"
    SortExpression"UnitPrice"
  • HeaderText"UnitPrice" DataFormatString"0C"
    gt
  • ltHeaderStyle HorizontalAlign"Right"gtlt/HeaderSty
    legt
  • ltItemStyle HorizontalAlign"Right"
    Width"100px"gtlt/ItemStylegtlt/aspBoundColumngt
  • ltaspBoundColumn DataField"UnitsInStock"
    HeaderText"UnitsInStock"gt
  • ltItemStyle HorizontalAlign"Right"gtlt/ItemStyle
    gt
  • lt/aspBoundColumngt
  • lt/Columnsgt
  • ltPagerStyle HorizontalAlign"Center"
    ForeColor"330099" BackColor"FFFFCC"
  • PageButtonCount"4" Mode"NumericPages"gtlt/PagerSt
    ylegt
  • lt/aspdatagridgtlt/Pgtlt/formgtlt/bodygtlt/HTMLgt

68
Code Behind (Page Loading)
  • Private Sub Page_Load(ByVal sender As
    System.Object, _
  • ByVal e As System.EventArgs) Handles MyBase.Load
  • ' Put user code to initialize the page
    here if desired
  • ' or Use Property Builder at design time
  • With DataGrid1
  • ' Enable paging.
  • .AllowPaging True
  • ' Display 4 page numbers at a time.
  • .PagerStyle.Mode PagerMode.NumericPa
    ges
  • .PagerStyle.PageButtonCount 4
  • .PageSize 5
  • End With
  • Dim dv As DataView
  • If Not IsPostBack Then
  • dv GetProductDV()
  • dv.Sort ""
  • DataGrid1.DataSource dv
  • DataGrid1.DataBind()
  • End If

69
Continued (Get Product View)
  • Protected recordCount As Integer
  • Private Function GetProductDV() As DataView
  • ' declare recordCount as an instance
    variable
  • Dim dvProduct As DataView
  • If Cache("ProductDV") Is Nothing Then
  • OleDbDataAdapter1.Fill(DsProduct1)
  • dvProduct DsProduct1.Tables(0).Defau
    ltView()
  • Cache("ProductDV") dvProduct
  • Else
  • dvProduct Cache("ProductDV")
  • End If
  • recordCount dvProduct.Count
  • Return dvProduct
  • End Function

70
Continued (Handling Paging)
  • Private Sub DataGrid1_PageIndexChanged( _
  • ByVal source As Object, ByVal e As _
  • System.Web.UI.WebControls.DataGridPageChangedEven
    tArgs) _
  • Handles DataGrid1.PageIndexChanged
  • Dim dv As DataView
  • dv GetProductDV()
  • DataGrid1.CurrentPageIndex e.NewPageIndex
  • If Not (Viewstate("sortexp") Is Nothing)
    And _
  • Not (ViewState("sortdirection") Is
    Nothing) Then
  • dv.Sort ViewState("sortexp") _
  • ViewState("sortdirection")
  • End If
  • DataGrid1.DataSource dv
  • DataGrid1.DataBind()
  • End Sub

71
Continued (Customized Footer output)
  • Private Sub DataGrid1_ItemCreated(ByVal sender As
    Object, _
  • ByVal e As System.Web.UI.WebControls.DataGridIte
    mEventArgs) _
  • Handles DataGrid1.ItemCreated
  • Dim elemType As ListItemType
    e.Item.ItemType
  • If elemType ListItemType.Footer Then
  • Dim tcc As TableCellCollection
    e.Item.Cells
  • Dim colCount As Integer tcc.Count
  • Dim i As Integer
  • For i 0 To colCount - 2
  • e.Item.Cells.RemoveAt(1)
  • Next ' One cell left in the table
    row
  • Dim c As TableCell e.Item.Cells(0)
  • c.ColumnSpan colCount
  • c.Font.Bold True
  • c.Text recordCount " records
    found. "
  • c.Text " Total "
    DataGrid1.PageCount.ToString() " pages."
  • End If
  • End Sub

Merge cells of the Footer into a single cell
72
Code - (With Sorting)
  • Private Sub DataGrid1_SortCommand(ByVal source
    As Object, _
  • ByVal e As System.Web.UI.WebControls.DataGridSort
    CommandEventArgs) _
  • Handles DataGrid1.SortCommand
  • Dim dv As DataView
  • dv GetProductDV()
  • Dim ordering As String
  • If Viewstate("sortexp") Is Nothing Then
  • ordering " ASC"
  • Else
  • If ViewState("sortexp")
    e.SortExpression Then
  • If ViewState("direction") Is
    Nothing Then
  • ordering " DESC"
  • Else
  • If ViewState("direction") "
    ASC" Then
  • ordering " DESC"
  • Else
  • ordering " ASC"
  • End If
  • End If

You can sort the a column in ASCending or
DESCending order and reverse the order back and
forth.
73
Using a DataGrid Web Control to Read and Write
Data
Reference VS.NET Online Help Walkthrough Using
a DataGrid Web Control to Read and Write Data
74
(No Transcript)
75
Create a Button Column in the Property Builder
  • Evoke the property builder. Insert the "Edit,
    Update, Cancel" button.

76
CategoryManage.aspx
  • lt_at_ Page Language"vb" AutoEventWireup"false"
  • Codebehind"CategoryManage.aspx.vb"
    Inherits"adogrid.CategoryManage"gt
  • ltHTMLgtltHEADgtlttitlegtCategoryManagelt/titlegtlt/HEADgtltb
    odygt
  • ltH1gtMaintain Category Tablelt/H1gt
  • ltform id"Form1" method"post" runat"server"gt
  • ltaspDataGrid idDataGrid1 runat"server"
    Height"295px" Width"499px"
  • DataSource"lt DsCategory1 gt"
    DataKeyField"CategoryID"
  • DataMember"Categories" AutoGenerateColumns"Fals
    e"
  • BorderColor"Black" BorderWidth"5px"gt
  • ltHeaderStyle Font-Bold"True"gtlt/HeaderStylegt
  • ltColumnsgt
  • ltaspBoundColumn DataField"CategoryID"
  • HeaderText"Category ID"gtlt/aspBoundColumngt
  • ltaspBoundColumn DataField"CategoryName"
  • HeaderText"Category Name"gtlt/aspBoundColumngt
  • ltaspBoundColumn DataField"Description"
    HeaderText"Description"gt
  • ltHeaderStyle Width"250px"gtlt/HeaderStylegtlt
    /aspBoundColumngt
  • ltaspEditCommandColumn ButtonType"PushButton"
    UpdateText"Update"
  • HeaderText"Commands" CancelText"Cancel"

77
Code Behind
  • Private Sub Page_Load(ByVal sender As
    System.Object, _
  • ByVal e As System.EventArgs) Handles MyBase.Load
  • OleDbDataAdapter1.Fill(DsCategory1)
  • If Not IsPostBack Then ' DataBind()
    only at first page_load event
  • DataGrid1.DataBind() ' Not when
    postback!
  • End If
  • End Sub
  • Private Sub DataGrid1_EditCommand ( ByVal source
    As Object, ByVal e _
  • As System.Web.UI.WebControls.DataGridCommandEvent
    Args) _
  • Handles DataGrid1.EditCommand
  • DataGrid1.EditItemIndex
    e.Item.ItemIndex
  • DataGrid1.DataBind()
  • End Sub
  • Private Sub DataGrid1_CancelCommand(ByVal source
    As Object, ByVal e _
  • As System.Web.UI.WebControls.DataGridCommandEvent
    Args) _
  • Handles DataGrid1.CancelCommand
  • DataGrid1.EditItemIndex -1
  • DataGrid1.DataBind()
  • End Sub

78
Continued
  • Private Sub DataGrid1_UpdateCommand(ByVal source
    As Object, ByVal e As _
  • System.Web.UI.WebControls.DataGridCommandEventArg
    s) _
  • Handles DataGrid1.UpdateCommand
  • Dim CategoryName, Description,
    categoryID As String
  • ' Gets the value of the key field of the
    row being updated
  • Dim key As String DataGrid1.DataKeys(e.I
    tem.ItemIndex).ToString
  • ' Get the value of the controls
    (textboxes) that the user
  • ' updated. The DataGrid columns are
    exposed as the Cells collection.
  • ' Each cell has a collection of controls.
    In this case, there is only one
  • ' control in each cell -- a TextBox
    control. To get its value,
  • ' you copy the TextBox to a local
    instance (which requires casting)
  • ' and extract its Text property.
  • Dim tb As TextBox
  • ' Gets the value the TextBox control in
    the 2nd column
  • tb CType(e.Item.Cells(1).Controls(0),
    TextBox)
  • CategoryName tb.Text
  • ' Gets the value the TextBox control in
    the 3rd column
  • tb CType(e.Item.Cells(2).Controls(0),
    TextBox)
  • Description tb.Text

79
Continued
  • ' Finds the row in the dataset table that
    matches the one the
  • ' user updated in the grid. This example
    uses a special Find method
  • ' defined for the typed dataset, which
    returns a reference to the row.
  • Dim r As DsCategory.CategoriesRow '
    Strong Type Datatset
  • r DsCategory1.Categories.FindByCategoryI
    D(key)
  • ' Updates the row r in the dataset
    table.
  • r.CategoryName CategoryName
  • r.Description Description
  • ' Send the changes rows via DataAdapter
    to update the database
  • OleDbDataAdapter1.Update(DsCategory1.GetCh
    anges())
  • DsCategory1.AcceptChanges()
  • ' Takes the DataGrid row out of editing mode
  • DataGrid1.EditItemIndex -1
  • ' Refreshes the grid
  • DataGrid1.DataBind()
  • End Sub

80
Disconnected Access to Data Using Datasets
Business Tier ASP.NET or Web Services
Presentation Tier
Data Tier
Web Form
Window Form
Data Set
Database



Data Gid









Data Set
Data Adapter
XML
XML
Data Connection
Web Form



Data Adapter



HTML
Data Connection
Browser
Internet Intranet
Business to Business
81
ASP.NET Topics
  • Creating Web forms
  • Processing form data
  • Validation Controls
  • State Management
  • Creating User Controls (Pagelets)
  • Creating Custom Web Server Controls
  • Error handling, tracing and debugging
  • ADO.Net and Data-Bound Web Server Controls
  • Using classes to increase code reuse
  • Mobile Internet Toolkit for building wireless web
    applications
  • Working with XML
  • Creating and consuming Web Services
  • Working with stored procedures
  • Working with Files, Email, and Graphics
  • Configuration and Deployment
  • Security
  • Building a shopping cart

82
Curriculum
  • Skills related to learning ASP.NET
  • HTML
  • Basic programming
  • SQL language and relational database concepts
  • Server-side scripting (ASP, ColdFusion, JSP, CGI,
    PHP)
  • Object-Oriented Programming
  • Offer ASP.NET as part of the Web Programming
    course.
  • Offer ADO.NET as part of a Database Programming
    and Client/Server computing class.
  • Offer ASP.NET and ADO.NET as part of the
    E-Business/E-Commerce Systems Development course.

83
References
  • http//www.asp.net/
  • http//samples.gotdotnet.com/quickstart/aspplus/
  • http//www.swarren.net
  • Free ASP.NET hosting account at
    http//www.brinkster.com/AboutGeneral.asp
  • Microsoft MCSD Certification Requirements
    http//www.microsoft.com/traincert/mcp/mcsd/requir
    ementsdotnet.asp
  • Visual Studio .Net Online Help
  • Overview of ADO.NET
  • Walkthrough Using a DataGrid Web Control to Read
    and Write Data
  • Introduction to ASP.NET, Kathleen Kalata, Course
    Technology, 2002.

84
References
  • MCAD/MCSD Self-Paced Training Kit Developing Web
    Applications with Microsoft Visual Basic .NET and
    Microsoft Visual C .NET, ISBN 0-7356-1584-5,
    Microsoft Press, 2002.
  • ASP.NET Unleashed by Stephen Walther, Sams
    Publishing, 2002.
  • ASP .NET Developer's Guide by Greg Buczek,
    McGraw-Hill/Osborne, 2002
  • ASP.NET Step by Step, G. Andrew Duthie, Microsoft
    Press.
  • Designing Microsoft ASP.NET Applications,
    Douglas J. Reilly, Microsoft Press, 2001.
  • Building Web Solutions with ASP.NET and ADO.NET,
    Dino Esposito, Microsoft Press, 2002.
  • Web Database Development Step by Step .NET
    Edition, Jim Buyens, Microsoft Press, 2002.
  • Microsoft ADO.NET Step by Step, Rebecca M.
    Riordan, Microsoft Press, 2002.
  • Microsoft ADO.NET (Core Reference), David
    Sceppa, Microsoft Press, 2002.
Write a Comment
User Comments (0)
About PowerShow.com