ASP.NET ® Web Applications and Database Processing ASP.NET.

85
ASP.NET ® Web Applications and Database Processing ASP.NET

Transcript of ASP.NET ® Web Applications and Database Processing ASP.NET.

Page 1: ASP.NET ® Web Applications and Database Processing ASP.NET.

ASP.NET® Web Applications and Database Processing

ASP.NET

Page 2: 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

Page 3: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 4: ASP.NET ® Web Applications and Database Processing ASP.NET.

DataReader.aspx

Page 5: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 6: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 7: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 8: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 9: ASP.NET ® Web Applications and Database Processing ASP.NET.

A Stored Procedure• Create stored procedure

CREATE PROCEDURE dbo.CategoryList

AS

SELECT *

FROM Categories

ORDER BY CategoryID

RETURN

Page 10: ASP.NET ® Web Applications and Database Processing ASP.NET.

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"

Page 11: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 12: ASP.NET ® Web Applications and Database Processing ASP.NET.

Stored Procedures with Parameters• Create stored procedure

CREATE PROCEDURE dbo.SubCategoryByCategory

@CategoryID int

AS

SELECT *

FROM SubCategories

WHERE CategoryID = @CategoryID

ORDER BY SubCategoryID

RETURN

Page 13: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 14: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 15: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 16: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 17: ASP.NET ® Web Applications and Database Processing ASP.NET.

DataViewProducts.aspx

Page 18: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 19: ASP.NET ® Web Applications and Database Processing ASP.NET.

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"

Page 20: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 21: ASP.NET ® Web Applications and Database Processing ASP.NET.

Item Collections of the DataView

Page 22: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 23: ASP.NET ® Web Applications and Database Processing ASP.NET.

PageSortProducts.aspx

Page 24: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 25: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 26: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 27: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 28: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 29: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 30: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 31: ASP.NET ® Web Applications and Database Processing ASP.NET.

DataSetSearch.aspx

Page 32: ASP.NET ® Web Applications and Database Processing ASP.NET.

Products.aspx

"menu.gif" andan image map

"menu.gif" andan image map

Page 33: ASP.NET ® Web Applications and Database Processing ASP.NET.

Products.aspx

Page 34: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 35: ASP.NET ® Web Applications and Database Processing ASP.NET.

Products.aspx—HTML view (Page 2)

<HeaderStyle ForeColor="Navy" BackColor="Silver"> </HeaderStyle>

<FooterStyle BackColor="Silver"> </FooterStyle>

Page 36: ASP.NET ® Web Applications and Database Processing ASP.NET.

Products.aspx—HTML view (Page 3)

<Columns>

<asp:TemplateColumn HeaderText="Image">

<HeaderStyle HorizontalAlign="Center"> </HeaderStyle> <ItemStyle HorizontalAlign="Center"> </ItemStyle>

Page 37: ASP.NET ® Web Applications and Database Processing ASP.NET.

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>

Page 38: ASP.NET ® Web Applications and Database Processing ASP.NET.

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>

Page 39: ASP.NET ® Web Applications and Database Processing ASP.NET.

Products.aspx—HTML view (Page 6)

</Columns>

<PagerStyle NextPageText="Next" PrevPageText="Previous" ForeColor="Red" Position="TopAndBottom"> </PagerStyle>

</asp:datagrid>

Page 40: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 41: ASP.NET ® Web Applications and Database Processing ASP.NET.

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"

Page 42: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 43: ASP.NET ® Web Applications and Database Processing ASP.NET.

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 &quot;" _ & strCategoryName " & "&quot; items found is " _ & dvProducts.Count.ToString

Page 44: ASP.NET ® Web Applications and Database Processing ASP.NET.

Products.aspx—Page_Load (Page 5)

dgProducts.DataSource = dvProducts

If Not Page.IsPostBack Then Page.DataBind() End If

End If

End Sub

Page 45: ASP.NET ® Web Applications and Database Processing ASP.NET.

Products.aspx—dgProducts_PageIndexChangedPrivate Sub dgProducts_PageIndexChanged( … ,

ByVal e As DataGridPageChangedEventArgs) Handles dgProducts.PageIndexChanged

dgProducts.CurrentPageIndex = _ e.NewPageIndex Page.DataBind()

End Sub

Page 46: ASP.NET ® Web Applications and Database Processing ASP.NET.

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)

Page 47: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 48: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 49: ASP.NET ® Web Applications and Database Processing ASP.NET.

InsertCat.aspx

Page 50: ASP.NET ® Web Applications and Database Processing ASP.NET.

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 (?, ?, ?, ?, ?)"

Page 51: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 52: ASP.NET ® Web Applications and Database Processing ASP.NET.

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)

Page 53: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 54: ASP.NET ® Web Applications and Database Processing ASP.NET.

Declaring a Parameter (Page 4)

• Example:Dim pparamCatID As New

OleDbParameter("CategoryID", OleDbType.Integer, 0, "CategoryID")

Page 55: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 56: ASP.NET ® Web Applications and Database Processing ASP.NET.

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"

Page 57: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 58: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 59: ASP.NET ® Web Applications and Database Processing ASP.NET.

Inserting a New Record with Stored Procedures and Parameters

Page 60: ASP.NET ® Web Applications and Database Processing ASP.NET.

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)

Page 61: ASP.NET ® Web Applications and Database Processing ASP.NET.

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)

Page 62: ASP.NET ® Web Applications and Database Processing ASP.NET.

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)

Page 63: ASP.NET ® Web Applications and Database Processing ASP.NET.

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)

Page 64: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 65: ASP.NET ® Web Applications and Database Processing ASP.NET.

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)

Page 66: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 67: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 68: ASP.NET ® Web Applications and Database Processing ASP.NET.

The <asp:LinkButton> Control (Page 2)

• Example:<ItemTemplate>

<asp:LinkButton ID="RemoveButton" CommandName="RemoveFromCat" Text="Delete" ForeColor="blue" runat="server" />

</ItemTemplate>

Page 69: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 70: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 71: ASP.NET ® Web Applications and Database Processing ASP.NET.

DeleteCat.aspx

Page 72: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 73: ASP.NET ® Web Applications and Database Processing ASP.NET.

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"

Page 74: ASP.NET ® Web Applications and Database Processing ASP.NET.

<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

Page 75: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 76: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 77: ASP.NET ® Web Applications and Database Processing ASP.NET.

• 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

Page 78: ASP.NET ® Web Applications and Database Processing ASP.NET.

• 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

Page 79: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 80: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 81: ASP.NET ® Web Applications and Database Processing ASP.NET.

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)

Page 82: ASP.NET ® Web Applications and Database Processing ASP.NET.

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

Page 83: ASP.NET ® Web Applications and Database Processing ASP.NET.

EditCat.aspx

Page 84: ASP.NET ® Web Applications and Database Processing ASP.NET.

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;

Page 85: ASP.NET ® Web Applications and Database Processing ASP.NET.

SELECT with Join (Page 2)

• Example:SELECT ProductID, ModelName, CategoryName

FROM Products, Categories

WHERE Products.CategoryID = Categories.CategoryID