asp.net ® web applications and database processing asp.net
TRANSCRIPT
ASP.NET® Web Applications and Database Processing
ASP.NET
Using Data Sources in VS.NET • The process of binding the data is the same regardless
of the data source– DataReader—provides a read-only, sequential direct
(on-line) connection to the data source– DataSet—accesses data as multiple DataTables– DataTable—one table returned from the DataSet– DataView—provides for alternate methods of looking
at DataTables including sorting, filtering and searching functionallity
The DataReader Object• Retrieves a read-only, non-buffered stream of data
from a database• Only one record at any time is stored in memory
– When a new record is read, the old record is removed from memory first
• The stream of data is retrieved sequentially• There are two classes that implement DataReader
– SqlDataReader is used for SQL Server databases– OleDbDataReader is used for other OLE DB
databases
DataReader.aspx
Using a DataReader Object (Page 1)
1. Instantiate Connection and Command objects
2. Declare SqlDataReader or OleDbDataReader object Dim dataReaderCategories As
OleDbDataReader
3. Assign a connection string to the connection object's ConnectionString property
4. Call the Open method for the connection object conTaraStore.Open()
5. Assign the connection object to the Connection property of the command object
Using a DataReader Object (Page 2)
6. Assign a SQL command string to the CommandText property of the command object
7. Call ExecuteReader method of the command object and assign the return value (reference to the disk file) to the DataReader object dataReaderCategories =
cmdCategories.ExecuteReader
Using a DataReader Object (Page 3)
8. Loop through the records of the DataReader object calling the Read method (returns a Boolean value indicating if there are more records)Do While dataReaderCategories.Read
strCategories &= dataReaderCategories("CategoryName")
Loop
9. Call the Close method for the connection and DataReader objects
Comparing OleDbDataReader and SqlDataReader• For related OleDb the objects are:
– OleDbConnection– OleDbCommand
• For related SqlClient the objects (from the System.Data.SqlClient namespace) are:– SqlConnection– SqlCommand
• Processing steps are the same for both
A Stored Procedure• Create stored procedure
CREATE PROCEDURE dbo.CategoryList
AS
SELECT *
FROM Categories
ORDER BY CategoryID
RETURN
DataReader and Stored Procedures (Page 1)
SqlConnection1 = New System.Data.SqlClient.SqlConnection
SqlConnection1.ConnectionString = "workstation id=KALATA;packet size=4096;user id=sa;data source=""(local)\NetSDK"";persist security info=True;initial catalog=Ch8TaraStoreSQL;password=password"
DataReader and Stored Procedures (Page 2)
SqlConnection1.Open()
Dim objCM As New SqlClient.SqlCommand("CategoryList", SqlConnection1)
objCM.CommandType = CommandType.StoredProcedure
Dim objDR As SqlClient.SqlDataReader
objDR = objCM.ExecuteReader(CommandBehavior.CloseConnection)
MyList.DataSource = objDR
MyList.DataBind()
Stored Procedures with Parameters• Create stored procedure
CREATE PROCEDURE dbo.SubCategoryByCategory
@CategoryID int
AS
SELECT *
FROM SubCategories
WHERE CategoryID = @CategoryID
ORDER BY SubCategoryID
RETURN
DataReader and Stored Procedures with Parameters (Page 1)
SqlConnection1 = New System.Data.SqlClient.SqlConnection
SqlConnection1.ConnectionString = "workstation id=KALATA;packet size=4096;user id=sa;data source=""(local)\NetSDK"";persist security info=True;initial catalog=Ch8TaraStoreSQL;password=password"
SqlConnection1.Open()
Dim objCM2 As New SqlCommand("SubCategoryByCategory", SqlConnection1)
objCM2.CommandType = CommandType.StoredProcedure
DataReader and Stored Procedures with Parameters (Page 2)
Dim paramCatID = New SqlParameter("@CategoryID", SqlDbType.Int, 4)
paramCatId.Value = txtCatID.Text.ToString()
objCM2.Parameters.Add(paramCatID)
Dim objDR2 As SqlDataReader
objDR2 = objCM2.ExecuteReader(CommandBehavior.CloseConnection)
MyCatList.DataSource = objDR2
MyCatList.DataBind()
Retrieving Data with Data View (Page 1)
• The DataView object returns a customized view of a DataTable
• Format to declare and instantiate:Dim dataViewName As DataView
…
dataViewName = dataSetName.Tables(0).DefaultView
Retrieving Data with Data View (Page 2)
• Example:dvProducts =
dsProducts.Tables(0).DefaultView– The DefaultView property for a Tables object returns a
reference that can be sorted, filtered and searched (as opposed to a custom view)
• To filter records of a DataView ,use the RowFilter property:dvProducts.RowFilter = "SubCategoryID = 19"– The string must be in valid SQL WHERE clause format
DataViewProducts.aspx
Using the DataView Object (Page 1)
1. Assign a ConnectionString property to the Connection object
2. Assign a CommandText property to the Command object
3. Assign the Connection object to the Command object's Connection property
4. Assign the Command object to the DataAdapter's SelectCommand property
5. Call the DataAdapter to Fill the DataSet
Using the DataView Object (Page 2)
6. Assign a subset of the DataSet to the DataView dvProducts =
dsProducts.Tables(0).DefaultView
7. Assign the RowFilter property of DataView to limit rows returned if desired dvProducts.RowFilter = "SubCategoryID = 19"
Using the DataView Object (Page 3)
8. Assign the DataView object to the DataGrid object's DataSource property dgProducts.DataSource = dvProducts
9. Bind the controls to data source, i.e. Page.DataBind()
–or–
dgProducts.DataBind()
Item Collections of the DataView
Customizing the DataGrid Control• In addition to Bound columns in which data from a
data source is bound to the column display, other supported operations include: – Sorting, Paging, and Filtering of data when its
DataSource property is set to a DataView object– Unbound columns which display additional content
such as link buttons and other form fields• Configured either in the code behind the page, using
visual (GUI) tools, or the PropertyBuilder
PageSortProducts.aspx
Sorting a DataGrid (Page 1)
• A Link Button control is placed at top of the column– Created by setting:
• AllowSorting property for DataGrid to True• SortExpression property for each BoundColumn to
the data field
– Data sorted by that column when user clicks it
Sorting a DataGrid (Page 2)
• The rows actually are not sorted in the DataGrid but rather in the DataView– Clicking the Link Button of the DataGrid object raises
(calls) a SortCommand event– A sort expression is passed to the called procedure
represented as e.SortExpression– Assign that value to Sort property of DataView object– Then re-bind the DataGrid
Sorting a DataGrid (Page 3)
• Sample code for the SortCommand event:Private Sub dgProducts_SortCommand( … ,
ByVal e As DataGridSortCommandEventArgs) Handles dgProducts.SortCommand
dvProducts.Sort = e.SortExpression
dgProducts.DataBind()
Paging within a DataGrid (Page 1)
• Displays subset of records in the control– The navigation bar displays LinkButtons for browsing
to previous or next pages– Default number of records (10) displayed may be
modified using the PageSize property– Set AllowPaging property to True
• Clicking a pager (navigation) button on the DataGrid– Raises the PageIndexChanged event which passes a
new page number to the e.NewPageIndex parameter– Assign that value to CurrentPageIndex property of the
DataGrid control
Paging within a DataGrid (Page 2)
• Sample code for the PageIndexChanged event:Private Sub
dgProducts_PageIndexChanged( … , ByVal e As DataGridPageChangedEventArgs) Handles dgProducts.PageIndexChanged
dgProducts.CurrentPageIndex = e.NewPageIndex
dgProducts.DataBind()
The PagerStyle Tag • Places a pager (navigation) button onto DataGrid
– Provides interface for paging to previous or next page• Properties:
– NextPageText—click on this text to advance to next page
– PrevPageText—click on this text to advance to previous page
– Position—valid positions for the pager are "Top", "Bottom" and both "TopAndBottom"
• Updateable in Property Builder
The RowFilter Property • For a DataGrid, temporarily selects subset of records
– Does not remove data from the DataView• The RowFilter property is assigned a criteria string
in format of a SQL WHERE clause• When the filter is removed, records are redisplayed
within the Web page• Example:
strMySearch = "ModelName LIKE '*" & txtSearch.Text & "*'"
dvProducts.RowFilter = strMySearch
DataSetSearch.aspx
Products.aspx
"menu.gif" andan image map
"menu.gif" andan image map
Products.aspx
Products.aspx—HTML view (Page 1)
<asp:datagrid id="dgProducts" style="Z-INDEX: 103; LEFT: 167px; TOP: 147px POSITION: absolute;" runat="server" Font-Names="Verdana" ForeColor="#004040" Font-Size="X-Small" Height="359px" Width="575px" AutoGenerateColumns="False" ShowFooter="True" AllowPaging="True">
Products.aspx—HTML view (Page 2)
<HeaderStyle ForeColor="Navy" BackColor="Silver"> </HeaderStyle>
<FooterStyle BackColor="Silver"> </FooterStyle>
Products.aspx—HTML view (Page 3)
<Columns>
<asp:TemplateColumn HeaderText="Image">
<HeaderStyle HorizontalAlign="Center"> </HeaderStyle> <ItemStyle HorizontalAlign="Center"> </ItemStyle>
Products.aspx—HTML view (Page 4)
<ItemTemplate> <a href='images/ProductPics/ <%# Container.DataItem( "ProductImage")%>'> <img src='images/ProductThumbnails/ <%# Container.DataItem( "Thumbnail") %>' border="0"> </a> </ItemTemplate>
</asp:TemplateColumn>
Products.aspx—HTML view (Page 5)
<asp:BoundColumn DataField="ModelName" HeaderText="Product Name"> </asp:BoundColumn>
<asp:BoundColumn DataField="UnitCost" HeaderText="Price" DataFormatString="{0:C}">
<HeaderStyle HorizontalAlign="Right"> </HeaderStyle> <ItemStyle HorizontalAlign="Right"> </ItemStyle>
</asp:BoundColumn>
Products.aspx—HTML view (Page 6)
</Columns>
<PagerStyle NextPageText="Next" PrevPageText="Previous" ForeColor="Red" Position="TopAndBottom"> </PagerStyle>
</asp:datagrid>
Products.aspx—Page_Load (Page 1)
Private Sub Page_Load(ByVal … ) Handles …
If Page.Request.QueryString.Count > 0 Then
Dim conTaraStore As New OleDbConnection Dim daProducts As New OleDbDataAdapter Dim cmdProducts As New OleDbCommand Dim dsProducts As New DataSet Dim dvProducts As DataView
Products.aspx—Page_Load (Page 2)
Dim strCategoryID As String _ = Page.Request.QueryString("ID") Dim strCategoryName As String
conTaraStore.ConnectionString = _"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=c:\Inetpub\wwwroot\Chapter8\data\TaraStore.mdb"
Products.aspx—Page_Load (Page 3)
cmdProducts.CommandText = _"SELECT ProductID, Products.CategoryID,
ModelName, ProductImage, UnitCost, Products.Thumbnail, CategoryName FROM Products, Categories WHERE Products.CategoryID = Categories.CategoryID ORDER BY ModelName"
cmdProducts.Connection = conTaraStore daProducts.SelectCommand = cmdProducts
Products.aspx—Page_Load (Page 4)
daProducts.Fill(dsProducts) dvProducts = _ dsProducts.Tables(0).DefaultView dvProducts.RowFilter = _ "CategoryID = " & strCategoryID strCategoryName = _ dvProducts.Item(0).Item( _ "CategoryName") lblResults.Text = "Number of "" _ & strCategoryName " & "" items found is " _ & dvProducts.Count.ToString
Products.aspx—Page_Load (Page 5)
dgProducts.DataSource = dvProducts
If Not Page.IsPostBack Then Page.DataBind() End If
End If
End Sub
Products.aspx—dgProducts_PageIndexChangedPrivate Sub dgProducts_PageIndexChanged( … ,
ByVal e As DataGridPageChangedEventArgs) Handles dgProducts.PageIndexChanged
dgProducts.CurrentPageIndex = _ e.NewPageIndex Page.DataBind()
End Sub
Data Updating with ASP.NET• Create new records, modify existing records, and
delete records (database maintenance)• Embed SQL INSERT, UPDATE, and DELETE
commands as strings into ASP.Net code• Methods for data retrieval and manipulation are built
into the various OleDb and SqlClient Data controls (either visual or programmatic)
The SQL INSERT Statement (Page 1)
• The INSERT command adds a row (record) to a table
• FormatINSERT INTO tableName
[(columnNames)]
VALUES (valueList … )
• Example (values must match the number of items, their order, and data types in the original table):INSERT INTO Categories
VALUES (30, "Irish Things", "30.jpg", "30.gif", "Irish Things", "30.ico");
The SQL INSERT Statement (Page 2)
• Example (empty values may be indicated by using the reserved word NULL):INSERT INTO Categories
VALUES (30, "Irish Things", NULL, NULL, "Irish Things", NULL)
• Example (a columnName list may be used if not all columns will be assigned a value):INSERT INTO Categories
(CategoryID, CategoryName, Description)
VALUES (30, "Irish Things", "Irish Things")
InsertCat.aspx
Parameters• A parameterized SQL statement is one which uses
question marks (?) to denote a parameter• A parameter is an object that can accept different
(variable) values based upon the logic of the running application
• The values are determined dynamically at run-time• Example:
cmdCategoriesInsert.CommandText = "INSERT INTO Categories VALUES (?, ?, ?, ?, ?)"
Declaring a Parameter (Page 1)
• Parameter objects to be used in SQL statements are instantiated from either the OleDbParameter or the SqlParameter class
• There should be one parameter object for each parameter in the SQL statement
• At run-time, when the SQL statement is executed, the current value of the parameter is substituted into the statement
Declaring a Parameter (Page 2)
• Format:Dim ParameterName As New
OleDbParameter("Name", OleDbType.dataType, size, "ColumnName")
– ParameterName is the name of the parameter object (it will be substituted into the SQL statement later by the Parameter.Add method)
– Name is the parameter name in the SQL statement (might be used to assign a value to the parameter)
– dataType matches data type in DataTable (may differ from Visual Basic .NET data type)
Declaring a Parameter (Page 3)
• Format:Dim ParameterName As New
OleDbParameter("Name", OleDbType.dataType, size, "ColumnName")
– size is the maximum size of data:• For a String it should match that of the DataTable• For numerics (including dates) and Boolean it should
be zero (0) since it will be inferred from its OleDbType
– ColumnName is the name of the column in the underlying DataTable
Declaring a Parameter (Page 4)
• Example:Dim pparamCatID As New
OleDbParameter("CategoryID", OleDbType.Integer, 0, "CategoryID")
• Stores the current value of a parameter which usually is updated by when a user modifies a column value in a DataRecord object
• Parameters also may be set manually in code• Formats:
CommandObject.Parameters("Name"/Index).Value = "String"/Value
ParameterObject.Value = "String"/Value
The Value Property for Parameters (Page 1)
The Value Property for Parameters (Page 2)
• Examples:cmdCategoriesInsert.Parameters("CategoryID"
).Value = intCatId
paramCatID.Value = intCatId
• So if the variable intCatId = 26 and the parameterized SQL statement reads:cmdCategories.CommandText = "SELECT * FROM
Categories WHERE CategoryID = ?"
• The actual statement which executes is:cmdCategories.CommandText = "SELECT * FROM
Categories WHERE CategoryID = 26"
Running the Query• The Open() method for the connection object must
be executed prior to running the query• The ExcuteQuery() method for a command object
executes a SQL INSERT, UPDATE or DELETE query
• Close() the connection after the query executes• Example:
conTaraStore.Open()
cmdCategories.ExecuteNonQuery()
conTaraStore.Close()
An INSERT Stored Procedure with Parameters
CREATE Procedure AddCatSQL( @CatName nvarchar(50), @CatImage nvarchar(50), @CatThumb nvarchar(50), @CatDesc ntext, @CatID int OUTPUT)ASINSERT INTO Categories (CategoryName, CatImage, Thumbnail, Description) VALUES (@CatName, @CatImage, @CatThumb, @CatDesc)SELECT @CatID = @@Identity
Inserting a New Record with Stored Procedures and Parameters
Inserting a New Record with Stored Procedures and Parameters (Page 1)
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim strConnection As String = _
"user id=sa;data source=(local)\NetSDK;" & _
"persist security info=True;" & _
"initial catalog=Ch8TaraStoreSQL;" & _
"password=password"
Dim SqlConnection1 As SqlConnection
SqlConnection1 = New SqlConnection(strConnection)
Inserting a New Record with Stored Procedures and Parameters (Page 2)
Dim oCM As SqlClient.SqlCommand
oCM = New SqlClient.SqlCommand("AddCatSQL", SqlConnection1)
oCM.CommandType = CommandType.StoredProcedure
Dim pCatID As New SqlClient.SqlParameter("@CatID", SqlDbType.Int, 4)
pCatID.Direction = ParameterDirection.Output
oCM.Parameters.Add(pCatID)
Inserting a New Record with Stored Procedures and Parameters (Page 3)
Dim pCatName As New SqlClient.SqlParameter("@CatName", SqlDbType.NVarChar, 50)
pCatName.Value = txtCatName.Text.ToString()
oCM.Parameters.Add(pCatName)
Dim pCatImage As New SqlClient.SqlParameter("@CatImage", SqlDbType.NVarChar, 50)
pCatImage.Value = txtCatImage.Text.ToString()
oCM.Parameters.Add(pCatImage)
Inserting a New Record with Stored Procedures and Parameters (Page 4)
Dim pCatThumb As New SqlClient.SqlParameter("@CatThumb", SqlDbType.NVarChar, 50)
pCatThumb.Value = txtCatThumb.Text.ToString()
oCM.Parameters.Add(pCatThumb)
Dim pCatDesc As New SqlClient.SqlParameter("@CatDesc", SqlDbType.NVarChar, 50)
pCatDesc.Value = txtCatDesc.Text.ToString()
oCM.Parameters.Add(pCatDesc)
Inserting a New Record with Stored Procedures and Parameters (Page 5)
SqlConnection1.Open()
ocm.ExecuteNonQuery()
SqlConnection1.Close()
txtCatName.Text = String.Empty
txtCatImage.Text = String.Empty
txtCatThumb.Text = String.Empty
txtCatDesc.Text = String.Empty
End Sub
The SQL DELETE Statement• Removes one or more records from a table• Format
DELETE FROM tableName
WHERE column_name = criteria;
• Example:DELETE FROM Products
WHERE ProductID = 499– If no WHERE clause, all rows would be deleted
(WHERE clause is relation condition)
Deleting Records with DataGrid• Uses a built-in TemplateColumn to display a button
– Create a programmer-defined "Delete" LinkButton– The DeleteCommand is a programmer-defined
method (Sub or Function) of Delete Column– The CommandName property names the procedure
or function to be called when the LinkButton is clicked
The <asp:LinkButton> Control (Page 1)
• Inserts a hyperlink-like text button into cells of the DataGrid which calls a Sub procedure when clicked
• The <asp:LinkButton> control is inserted in an <ItemTemplate> … <ItemTemplate> block
• Calls the ItemCommand event for the DataGrid control when the button is clicked
• The CommandName property is passed to the called procedure as an argument so program can determine which LinkButton was clicked
The <asp:LinkButton> Control (Page 2)
• Example:<ItemTemplate>
<asp:LinkButton ID="RemoveButton" CommandName="RemoveFromCat" Text="Delete" ForeColor="blue" runat="server" />
</ItemTemplate>
The ItemCommand Event• The Sub procedure that is called when a LinkButton
object in the DataGrid is clicked• Partial example:
Private Sub dgCategories_ItemCommand(ByVal source As System.Object, ByVal e DataGridCommandEventArgs) Handles dgCategories.ItemCommand
If e.CommandSource.CommandName = "RemoveFromCat" Then
…
The e.Item.Cells Collection• When the ItemCommand event executes, a reference is
passed to the e parameter representing the row (Item) that raised the event
• The Cells collection can be referenced by an index to return one cell object from the Item, i.e.e.Item.Cells(1)– References the second cell in the row where the
LinkButton was clicked• The reference may be stored in a TableCell object, i.e.
Dim CatIDCell As TableCell = e.Item.Cells(1).ToString()
DeleteCat.aspx
Updating Records with DataGrid• Enables editing by converting a row in the table
temporarily into text boxes• Creates a special hyperlink button that calls an
UpdateCommand event when update processing takes place
The SQL UPDATE Command• Modifies contents (value) of one or more fields in a
record or records– The SET clause is an assignment statement
• Format:UPDATE tableNameSET columnName = newValue, …WHERE columnName = criteria
• Example:UPDATE CategoriesSET CategoryName = "Irish Things"WHERE CategoryID = "32"
<asp:EditCommandColumn> Control• A special LinkButton column used for updating
rows in a DataGrid control• The text for the buttons by default are labeled Edit,
Update, and Cancel – The text for these may be changed by modifying
EditText, UpdateText, and CancelText properties• The events that are called when a user clicks on one
of the buttons for the DataGrid are respectively EditCommand, UpdateCommand and CancelCommand
EditItemIndex Property• When set to index of a selected row in a DataGrid,
the cells in the row are displayed as text boxes• The user may modify contents of one or more cells• Examples:
dgProducts.EditItemIndex = 3
dgProducts.EditItemIndex = e.Item.ItemIndex
• When the EditItemIndex property is set to -1, the editing feature of the DataGrid is turned off:dgProducts.EditItemIndex = -1
Controls Object of the Item.Cells• Retrieves the contents of a cell in a DataGrid control
(Item.Cells(n)) as a control object• Format:
e.Item.Cells(index).Controls(index)
• The following example uses the CType method (convert to type) to convert the control to a TextBox:
• Example:txtBox.Text = e.Item.Cells(2).Controls(0)– In this instance, the index for controls is 0 since there is
only one text box in each DataTable cell
• Enables editing of columns in a DataRow object• Temporarily suspends the RowChanging event on
the row that is being edited …– The row will be updated once at the end when the
EndEdit method executes• Format:
dataTableName.Rows(index).BeginEdit()
• Example:dtCategories.Rows(intIndex).BeginEdit()
The BeginEdit Method
• Disables editing of the DataRow object• Fires (calls) the RowChanging event to update the
entire record off-line• Format:
DataTableName.Rows(index).EndEdit()
• Example:dtCategories.Rows(intIndex).EndEdit()
The EndEdit Method
The Item Collection• Member of the DataRow object representing the one
column (field) returned from the row• Formats:
dataRowName.Item("FieldName"/index)
dataTableName.Rows(index).Item("FieldName"/index)
• Example:dtCategories.Rows(intIndex).Item("CatName")
The GetChanges Method• Examines an existing DataSet and returns (points to)
the changed records in the original DataSet– Inserts, updates and deletes
• Format:DataSetName.GetChanges()
• Example:Dim dsCategoriesUpdate As DataSet =
dsCategories.GetChanges()
The Update Method• Examines a DataSet (usually a new DataSet object
from previously executed GetChanges method) for information about inserted, updated or deleted records
• Executes the appropriate SQL statement to modify the underlying database table on disk
• Format:DataAdaptorName.Update(DataSetName)
• Example:daTaraStore.Update(dsCategoriesUpdate)
The AcceptChanges Method• Causes any records in the DataSet, that previously
were marked as having been changed, to be marked now as unchanged
• Usually called immediately after Update method has modified the underlying database table
• Format:DataSetName.AcceptChanges()
• Example:dsCategories.AcceptChanges()
EditCat.aspx
SELECT with Join (Page 1)
• A join operation links related fields from more than one table
• Column names that exist in more than a single table must be prefixed by the table name …– I.e. "Products.CategoryID"– Or "Categories.CategoryID"
• Format:SELECT columnNames …
FROM tableNameList …
WHERE primaryKey = foreignKey;
SELECT with Join (Page 2)
• Example:SELECT ProductID, ModelName, CategoryName
FROM Products, Categories
WHERE Products.CategoryID = Categories.CategoryID