Presentation is loading. Please wait.

Presentation is loading. Please wait.

ASP.NET Database Operations. Sorting with Repeater For this example, records from the Products table are sorted prior to their display in the Repeater.

Similar presentations


Presentation on theme: "ASP.NET Database Operations. Sorting with Repeater For this example, records from the Products table are sorted prior to their display in the Repeater."— Presentation transcript:

1 ASP.NET Database Operations

2 Sorting with Repeater For this example, records from the Products table are sorted prior to their display in the Repeater. Sorting is triggered by clicking a button that serves as the column heading. That is, when the "Name" button is clicked records are shown in ascending alphabetic order by product name; when the "Type" button is clicked, the records are ordered alphabetically by product type.

3 Sorting with Repeater Sorted Product Listing - _ Repeater

4 Sorting with Repeater Using Button Command Properties: When the "Number" button is clicked the OnCommand event handler calls the SortRepeater subprogram. An identifier, ItemNumber in this case, is also passed to the subprogram through the CommandName property. <asp:Button Text="Number" runat="server" _ OnCommand="SortRepeater " _ CommandName="ItemNumber" _ EnableViewState="False"/> Thus, the called subprogram receives a CommandName value that identifies the name of a field in the Products table on which sorting is to take place. Each of the buttons in the header row calls the same subprogram but names a different database field for sorting.

5 Sorting with Repeater An EnableViewState="False" property setting is made for the buttons. This ensures that the visual status of a button is not maintained in View State. A clicked button is "highlighted" with a bolder border than other buttons. Unless this emphasis is turn off between page postings, previous buttons that were clicked remain highlighted, making it difficult to tell which button was most recently clicked. This setting does not affect actual sorting of the records; it only affects the button's display characteristics.

6 Sorting with Repeater The Sort Subprogram. Record sorting takes place in the SortRepeater subprogram. Sorting requires no more than an SQL statement to retrieve records from the Products table in a particular order. That order is given by the CommandName argument passed to the subprogram by a button click. Sub SortRepeater (Src As Object, Args As _ CommandEventArgs) SQLString = "SELECT * FROM Products _ ORDER BY " & _ Args.CommandName DisplayRepeater End Sub

7 Sorting with Repeater Notice the signature for the subprogram includes Args As CommandEventArgs. CommandEventArgs is the object through which database fields names are passed to the subprogram. Args.CommandName is the property containing the name of the sort field that is passed. Therefore, this property is appended to a SELECT statement to return a recordset ordered by the values in that field. This single subprogram, then, can compose a proper SELECT statement for any of the buttons that are clicked.

8 Sorting with Repeater Issuing the SELECT Statement. Once a proper SELECT statement is prepared a "general-purpose" DisplayRepeater subprogram can be called to retrieve the recordset and rebind it to the Repeater. Sub DisplayRepeater DBConnection = New OleDbConnection( _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=d:\Databases\eCommerce.mdb") DBConnection.Open() DBCommand = New OleDbCommand(SQLString, DBConnection) DBReader = DBCommand.ExecuteReader() RepeaterDisplay.DataSource = DBReader RepeaterDisplay.DataBind() DBReader.Close() DBConnection.Close() End Sub In previous examples a SELECT statement was included in the database retrieval and binding routine. In this case the statement is composed in a different subprogram and just being issued in this routine.

9 Sorting with Repeater Page Loading. All that remains is to code the Page_Load portion of the page. The Repeater appears when the page loads, so an initial SQL statement needs to be issued to populate the Repeater this first time; subsequently it is redisplayed by the sort routine. Sub Page_Load If Not Page.IsPostBack Then SQLString = "SELECT * FROM Products _ ORDER BY ItemNumber“ DisplayRepeater End If End Sub SortRepeater.aspx

10 Sorting with Repeater On initial page load the SQLString retrieves a recordset sorted by ItemNumbers (any field could be chosen or none at all). Then the DisplayRepeater subprogram is called to extract and bind this initial recordset to the Repeater. You might note that the DisplayRepeater subprogram does not have a signature source and argument list. This is because no arguments are being passed to it. It is not being called by a server control; it is "our" subprogram to do with as we please. Also, since variable SQLString is referenced in two different subprograms (SortRepeater and DisplayRepeater) it needs to be declared as a global variable.

11 DataGrid FullDataGrid.aspx

12 Sorting with DataGrid Control An asp:DataGrid control can automatically use its column headings as links to sort routines. Minor changes are required to the control, and similar subprograms to the Repeater are needed. Using Link Command Properties: First, "permission" to sort the grid is provided by adding AllowSorting="True" and OnSortCommand="SortDataGrid" to the control's property list, the latter naming the subprogram to call when a link is clicked. Then, for those columns on which sorting is to take place, a SortExpression="sort field" property is added.

13 Sorting with DataGrid Control Sorted Product Listing - DataGrid <asp:BoundColumn DataField="ItemNumber" SortExpression="ItemNumber" HeaderText="No" HeaderStyle-Font-Size="8pt" ItemStyle-Font-Size="8pt"/>

14 Sorting with DataGrid Control Description <asp:BoundColumn DataField="ItemPrice" SortExpression="ItemPrice" HeaderText="Price" HeaderStyle-Font-Size="8pt" ItemStyle-Font-Size="8pt" ItemStyle-HorizontalAlign="Right"/>

15 Sorting with DataGrid Control <asp:BoundColumn DataField="ItemQuantity“ SortExpression="ItemQuantity" HeaderText="Qty" HeaderStyle-Font-Size="8pt" ItemStyle-Font-Size="8pt" ItemStyle-HorizontalAlign="Right"/> Picture _.jpg" style="height:50px; cursor:hand" title="Click for larger image" _ onClick="ShowPicture('.jpg')"/>

16 Sorting with DataGrid Control The Sort Subprogram. The SortDataGrid subprogram has a slightly different signature from the one used for the Repeater; plus, Args.SortExpression identifies the sort field passed through the link click. Sub SortDataGrid (Src As Object, Args As _ DataGridSortCommandEventArgs) SQLString = "SELECT * FROM Products _ ORDER BY " & Args.SortExpression DisplayDataGrid End Sub A SELECT statement is composed by appending the passed field name; then subprogram DisplayDataGrid is called.

17 Sorting with DataGrid Control Issuing the SELECT Statement. Once a SELECT statement is composed, subprogram DisplayDataGrid is called to retrieve the recordset and bind it to the DataGrid. This subprogram is identical to the one used for the Repeater except for the binding statements. Sub DisplayDataGrid DBConnection = New OleDbConnection( _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=d:\Databases\eCommerce.mdb") DBConnection.Open() DBCommand = New OleDbCommand(SQLString, DBConnection) DBReader = DBCommand.ExecuteReader() DataGridDisplay.DataSource = DBReader DataGridDisplay.DataBind() DBReader.Close() DBConnection.Close() End Sub

18 Sorting with DataGrid Control Page Loading. As is done for the Repeater, an initial SQL command is composed and issued through the DisplayDataGrid subprogram so that the DataGrid is initially populated with records when the page first opens. Sub Page_Load If Not Page.IsPostBack Then SQLString = "SELECT * FROM Products _ ORDER BY ItemNumber" DisplayRepeater DisplayDataGrid End If End Sub Since variable SQLString is referenced in two different subprograms (SortDataGrid and DisplayDataGrid) it needs to be declared as a global variable. SortDataGrid.aspx

19 DataList FullDataList.aspx

20 Sorting with DataList Control The asp:DataList control does not have a built-in sorting feature. Radio buttons are added to select a sort field and to indicate ascending or descending sequence. A button is added to call the SortDataList subprogram. Coding Sort Buttons: A table to format the radio buttons is added immediately below the caption for the DataList. The first set of buttons permits choice of a sort field; the second set is for choosing the direction of sort. A standard button calls the SortDataList subprogram.

21 Sorting with DataList Control Sorted Product Listing - DataList Order By:... Direction:

22 Sorting with DataList Control <asp:DataList id="DataListDisplay" runat="server" _ Width="560" _ CellSpacing="3" _ CellPadding="5" _ RepeatColumns="2" _ RepeatDirection="Horizontal" _ GridLines="Both" ItemStyle- _ BackColor="#F9F9F9" _ ItemStyle-Font-Size="8pt">

23 Sorting with DataList Control _.jpg" style="width:50px; float:left; margin-right:15px; _ margin-bottom:20px; cursor:hand" _ title="Click for larger image" onClick="ShowPicture('.jpg')"/> Number: Quantity: Description:

24 Sorting with DataList Control Coding the Sort Routine: As in previous examples the SortDataList subprogram creates an SQL statement that can be executed by the DisplayDataList routine. In this case two values are appended to the statement. The field name is given by the value of the checked radio button in the first set; the value ASC or DESC is given by the second set. The resulting SQL statement is in the format: SELECT * FROM Products _ ORDER BY 'field' ASC (or DESC).

25 Sorting with DataList Control Sub SortDataList (Src As Object, Args As EventArgs) SQLString = "SELECT * FROM Products _ ORDER BY " & _ SortButtons.SelectedItem.Value _ & " " & _ DirectionButtons.SelectedItem.Value DisplayDataList End Sub Sub DisplayDataList DBConnection = New OleDbConnection( _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=d:\Databases\eCommerce.mdb") DBConnection.Open() DBCommand = New OleDbCommand(SQLString, DBConnection) DBReader = DBCommand.ExecuteReader() DataListDisplay.DataSource = DBReader DataListDisplay.DataBind() DBReader.Close() DBConnection.Close() End Sub

26 Sorting with DataList Control An initial SQL command is composed and issued through the DisplayDataList subprogram when the page first opens. Sub Page_Load If Not Page.IsPostBack Then SQLString = "SELECT * FROM Products _ ORDER BY ItemNumber" DisplayDataList End If End Sub Since variable SQLString is referenced in two different subprograms (SortDataList and DisplayDataList) it needs to be declared as a global variable. SortDataList.aspx

27 Display Selected Records When displaying records from a database table it is often convenient to be able to select particular records for display. This involves specifying some criterion value for one of the fields and then extracting only those records which meet that criterion; for example, select only those records where the quantity in stock is greater than 100. The following Repeater is based on the previous control which permits record sorting. Selections are provided to choose subsets of records from the Products table which meet specified search criteria. For instance, the following subset shows all software for which the ItemType field equals "Database", sorted in ascending sequence by ItemPrice.

28 Display Selected Records In order to make the selection and sorting an SQL statement must be composed to read SELECT * FROM Products WHERE ItemType='Database' ORDER BY ItemPrice ASC Additional controls are added to the Repeater to collect information to create this statement. A drop- down list permits selection of a field name, a second drop-down list selects a conditional operator, and a textbox provides the value for comparison. These three controls permit creation of an SQL WHERE clause giving the criterion for selecting records from the Products table. A set of radio buttons is also added to specify their sort order.

29 Display Selected Records Selected Product Listing - Repeater <asp:Panel id="FieldPanel" BackColor="#F0F0F0" Width="560" _ runat="server"> Select Field:

30 Display Selected Records <asp:TextBox id="FieldValue" _ Text="Database" runat="server"/> <asp:RadioButtonList id="DirectionButtons“ _ runat="server" RepeatDirection="Horizontal" _ RepeatLayout="Flow"> <asp:ListItem Text="ASC" Value="ASC" _ Selected="True"/>

31 Display Selected Records <asp:Repeater id="RepeaterDisplay" _ runat="server"> <table id="RepeaterTable" border="1“ _ style="background-color:#F9F9F9"> <asp:Button Text="Number" runat="server“ _ OnCommand="SortRepeater“ _ CommandName="ItemNumber" _ EnableViewState="False"/>...

32 Display Selected Records

33 Display Selected Records Field name selection is made through an asp:DropDownList supplying field names in the Products table. The actual names are given in the Value properties. Select Field:

34 Display Selected Records Conditional operators are selected from a second DropDownList whose Values are the actual conditional operators and whose Text properties are verbal equivalents. " Text="Greater Than"/> " Text="Not Equal To"/> Finally, the search criterion is given in an asp:TextBox control. Values applied to SQL statements are not case sensitive, so either lower-case, upper-case, or mixed-case characters can be entered.

35 Composing SQL String The values from the three controls can be used to construct an SQL WHERE clause for selecting records that meet the criterion. For instance, when "ItemType" is selected from the FieldName list, and " = " is selected from the Operator list, and "Database" is entered in the FieldValue textbox, then concatenating the values " WHERE " & FieldName.SelectedItem.Value & _ Operator.SelectedItem.Value & "'" & FieldValue.Text & "'“ produces the string WHERE ItemType = 'Database' This string can be plugged into a SELECT statement to extract records based on this condition test. Composition of the SELECT statement takes place in the SortRepeater subroutine.

36 Display Selected Records Sub SortRepeater (Src As Object, Args As CommandEventArgs) SQLString = "SELECT * FROM Products" If FieldValue.Text <> "" Then If Operator.SelectedItem.Value = " LIKE " _ OR _ Operator.SelectedItem.Value = " Not LIKE " Then '-- "Contains" comparison, e.g., '-- WHERE field LIKE 'value' SQLString &= " WHERE " & FieldName.SelectedItem.Value _ & _ Operator.SelectedItem.Value & "'%" & FieldValue.Text _ & "%'" Else If FieldName.SelectedItem.Value <> "ItemPrice" AND _ FieldName.SelectedItem.Value <> "ItemQuantity" Then '-- Alphanumeric comparising, e.g., '-- WHERE field = 'value'

37 Display Selected Records SQLString &= " WHERE " & FieldName.SelectedItem.Value & _ Operator.SelectedItem.Value & "'" & FieldValue.Text & "'" Else '-- Numeric comparison, e.g., '-- WHERE field = value SQLString &= " WHERE " & FieldName.SelectedItem.Value _ & Operator.SelectedItem.Value & FieldValue.Text End If SQLString &= " ORDER BY " & Args.CommandName SQLString &= " " & DirectionButtons.SelectedItem.Value DisplayRepeater End Sub

38 Display Selected Records Composing the WHERE clause depends on the user having entered a search criterion value in the textbox. If the textbox is empty this part of the subprogram is not run and no WHERE clause is appended to the SQLString. The format of the WHERE clause differs slightly when specifying string versus numeric comparisons. When the comparison value is a string, it must be enclosed in single quotes (apostrophes); when the comparison value is a number, no quotes are used. For example, WHERE ItemSupplier = 'Microsoft' WHERE ItemPrice > 100 So, the script supplies different SQL coding for the ItemNumber, ItemType, ItemSupplier, ItemName, and ItemDescription fields (which are strings whose comparison values are enclosed in apostrophes) versus the ItemPrice and ItemQuantity fields (which are numbers whose comparison values are not enclosed in single quotes).

39 Display Selected Records When using LIKE or Not LIKE comparisons, all values are treated as strings and no differentiation in coding is made. The script uses the general field search LIKE '%value%' to locate the entered value anywhere in the field. After the WHERE clause is composed and appended to the SQLString variable, the ORDER BY clause is added. SQLString &= " ORDER BY " & Args.CommandName As before, the sort field is given by the CommandName associated with the button clicked in the column header. Next, either ASC or DESC is appended to the SQLString depending on which of the radio buttons is checked. SQLString &= " " & DirectionButtons.SelectedItem.Value Finally, the completed SQLString is issued by calling the DisplayRepeater subprogram. The Repeater is re-bound with records matching the search criterion and sorted according to the button click. SelectRepeater.aspx

40 Display Records w/Paging When displaying records from a database you need to be cautious about the length of output produced. The Products table includes only 20 records and easily fits on a single Web page. But consider a database table containing hundreds or thousands of records. It would be impractical to display all records at one time. The need is to display only a few records at a time and to provide a paging mechanism for looking through the complete table. In the following example, four records at a time from the Products table are displayed in a Repeater. Buttons call up the next set of records for viewing.

41 Display Records w/Paging Example uses buttons to display subsets of records from the Products table. Two issue surround these buttons. First, there needs to be a way to associate a particular button with a particular subset of records from the table. Second, the buttons must be created dynamically, under script control. They cannot be hard coded on the page because it is not known in advance how many buttons are needed nor which subset of records each is associated with. As records are added to the table, more buttons are needed; as records are deleted, fewer buttons are needed. The number of records in the table and, therefore, the number of buttons needed cannot be known until the table is first accessed in a script. Although button controls cannot be coded directly on the page, an area can be set aside as a "placeholder" where a script can place the buttons when it creates them. The asp:PlaceHolder control is designed for just this purpose. It reserves space on the Web page within which dynamically created controls can be placed. It has a very simple general format:

42 Display Records w/Paging Product Listing - Repeater No Type Supplier Name Description Price Qty Picture

43 Display Records w/Paging _.jpg" style="height:50px; cursor:hand" title="Click for larger image" _ onClick="ShowPicture('.jpg')"/> Page:

44 Display Records w/Paging Initial Repeater Display: The number of records per page to display is an arbitrary choice. In this example four records per page is chosen. When the page opens the first subset of records needs to be retrieved for display in the Repeater. This is done in the following portion of the script. Variable PageSize is declared to hold the number of records per page. SELECT TOP n * FROM table... to retrieve the first PageSize number of records from the Products table and bind them to the Repeater. This initial retrieval takes place only the first time the page loads.

45 Display Records w/Paging Dim DBConnection As OleDbConnection Dim DBCommand As OleDbCommand Dim DBReader As OleDbDataReader Dim SQLString As String Dim PageSize As Integer = 4

46 Display Records w/Paging Sub Page_Load If Not Page.IsPostBack Then '-- Display the first PageSize number of records DBConnection = New OleDbConnection( _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=d:\Databases\eCommerce.mdb") DBConnection.Open() SQLString = "SELECT TOP " & PageSize & " * FROM Products " & _ "ORDER BY ItemNumber" DBCommand = New OleDbCommand(SQLString, DBConnection) DBReader = DBCommand.ExecuteReader() RepeaterDisplay.DataSource = DBReader RepeaterDisplay.DataBind() DBReader.Close() DBConnection.Close() End If...create paging buttons End Sub

47 Display Records w/Paging Dynamic Paging Buttons: Since paging buttons are created in script they do not take part in the page's View State. They need to be created each time the page loads, within the script's Page_Load subroutine. Each paging button needs to represent a particular subset of records. When it calls a subprogram, say DisplayRepeater, to redisplay the Repeater and bind that subset of records it must pass along to the subprogram information about which subset to display. Here is an opportunity, then, to use the CommandName property of a button to pass this information to the subprogram. Records from the Products table are retrieved in ascending order by ItemNumber. Therefore, the information needed by subprogram DisplayRepeater is the first ItemNumber in the subset and the last ItemNumber in the subset. Assume for instance that the subset of records to be displayed begins with ItemNumber "GR1111" and ends with ItemNumber "GR4444". A command button containing this information could be coded as follows:

48 Display Records w/Paging That is, the button's OnCommand property calls subprogram DisplayRepeater, and its CommandName property is a string containing the first and last item numbers to be retrieved. These item numbers are separated by a "pipe" character (|) although any delimiter character could be used so long as it were not part of the values in the list. When the subprogram is called it could parse the CommandArgument argument to determine the range of item numbers to extract from the Products table. This is precisely the way the example Repeater works. The Page_Load script builds a set of buttons, each containing the starting and ending ItemNumbers for a subset of records. These item numbers are given in the CommandName property of the buttons.

49 Display Records w/Paging Determining Subsets of Records: The first task in creating the paging buttons is to retrieve the full set of item numbers from the Products table and to assign particular subsets of numbers to particular buttons. For this purpose an ArrayList is created and loaded with item numbers from the table. It is easier to work with a fully stocked ArrayList than try to create buttons while iterating through a recordset.

50 Display Records w/Paging Sub Page_Load If Not Page.IsPostBack Then...display initial Repeater End If '-- Load array ItemNumberList() with item numbers Dim ItemNumberList = New ArrayList() DBConnection = New OleDbConnection( _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=d:\Databases\eCommerce.mdb") DBConnection.Open() SQLString = "SELECT ItemNumber FROM Products _ ORDER BY ItemNumber"

51 Display Records w/Paging DBCommand = New OleDbCommand(SQLString, _ DBConnection) DBReader = DBCommand.ExecuteReader() While DBReader.Read() ItemNumberList.Add(DBReader("ItemNumber")) End While DBReader.Close() DBConnection.Close() ItemNumberList.TrimToSize()... End Sub

52 Display Records w/Paging At this point ArrayList ItemNumberList contains, in sequence, all of the item numbers from the Products table. Now it is a matter of indexing through the ArrayList, determining the beginning and ending item numbers of each subset of records, and creating a button for each subset.

53 Display Records w/Paging '-- Create Paging Buttons Dim StartIndex As Integer Dim EndIndex As Integer Dim StartKey As String Dim EndKey As String Dim i As Integer StartIndex = 0 For i = 1 To _ Math.Ceiling(ItemNumberList.Count / PageSize) '-- Determine starting and ending array indexes EndIndex = StartIndex + PageSize - 1 If EndIndex > RecordCount - 1 Then EndIndex = RecordCount - 1 End If

54 Display Records w/Paging '-- Assign starting and ending item numbers StartKey = ItemNumberList(StartIndex) EndKey = ItemNumberList(EndIndex) '-- Create a button and assign to placeholder Dim PageButton As Button PageButton = New Button() PageButton.Text = i PageButton.id = "P" & i PageButton.CommandArgument = StartKey & "|" & EndKey PageButton.Style("width") = "20px" PageButton.Style("background-color") = "#F0F0F0" AddHandler PageButton.Command, AddressOf DisplayRepeater PageButtons.Controls.Add(PageButton) StartIndex += PageSize Next

55 Display Records w/Paging The number of paging buttons needed is given by dividing the total number of item numbers in the array (ItemNumberList.Count) by the number of records per page (PageSize). More accurately, the Math.Ceiling() method must be applied to the formula to always "round up" to the next whole number of buttons: Math.Ceiling(ItemNumberList.Count / PageSize) A loop running from 1 to Math.Ceiling(ItemNumberList.Count / PageSize) produces the correct number of buttons to create. Each iteration of the loop produces one of those buttons.

56 Display Records w/Paging Each button requires a CommandName property composed of the first and last item numbers for its particular subset. The ArrayList index of these item numbers occurs in multiples of the PageSize. That is, for a Products table of 20 records retrieved 4 at a time the ArrayList locations of the beginning and ending item numbers for 5 buttons can be shown as: 1 (0)-(3), 2 (4)-(7), 3(8)-(11), 4 (12)-(15) The first portion of script within the loop determines these ArrayList indexes of the item numbers to assign to a button and extracts them from the array for assignment to variables StartKey and EndKey.

57 Display Records w/Paging StartIndex = 0 For i = 1 To Math.Ceiling(ItemNumberList.Count / PageSize) '-- Determine starting and ending array indexes EndIndex = StartIndex + (PageSize - 1) If EndIndex > ItemNumberList.Count - 1 Then EndIndex = ItemNumberList.Count - 1 End If

58 Display Records w/Paging '-- Assign starting and ending item numbers StartKey = ItemNumberList(StartIndex) EndKey = ItemNumberList(EndIndex)... StartIndex = EndIndex + 1 Next The StartIndex for the array (the index of the beginning item number for the first button) is 0. The EndIndex (the index of the ending item number for the first button) is StartIndex + (PageSize - 1). For the first button StartIndex = 0 and EndIndex = 3, spanning the four array elements containing the item numbers associated with this first button. Using these indexes, StartKey is assigned the item number in ItemNumberList(0) and EndKey is assigned the item number in ItemNumberList(3).

59 Display Records w/Paging At the end of the loop the StartIndex is moved forward to point to the array element following the previous EndIndex element (StartIndex = EndIndex + 1). During the next iteration of the loop StartIndex = 4 and EndIndex = 7, and the item numbers in array elements 4 and 7 get assigned to the second button. This indexing continues until all five buttons are created. Depending on the number of records in the Products table there is a good possibility that the last button retrieves fewer records than the other buttons. For example, if the table contains only 18 records then the last button retrieves only two records (4 + 4 + 4 + 4 + 2). This is why an "end-of-array" check is made when calculating the EndIndex for a button.

60 Display Records w/Paging EndIndex = StartIndex + (PageSize - 1) If EndIndex > ItemNumberList.Count - 1 Then EndIndex = ItemNumberList.Count - 1 End If If the calculation produces an index value that is beyond the upper limit of the array, then the EndIndex is set to that last element. In all of the calculations an index value is always one less than a count (ItemNumberList.Count - 1 and PageSize - 1). These adjustments are needed because arrays are indexed beginning with 0 and counts begin with 1.

61 Display Records w/Paging Creating Buttons with Scripts: The last section of code in the loop creates a new asp:Button control containing a CommandName property with a range of items numbers to be retrieved for display. '-- Create a button and assign to placeholder Dim PageButton As Button PageButton = New Button() PageButton.Text = i PageButton.id = "P" & i PageButton.CommandArgument = StartKey & "|" & EndKey PageButton.Style("width") = "20px" PageButton.Style("background-color") = "#F0F0F0" AddHandler PageButton.Command, AddressOf DisplayRepeater PageButtons.Controls.Add(PageButton)

62 Display Records w/Paging A button is created programmatically by assigning it to a reference variable with variable = New Button(), where variable is the programmer-supplied reference to the new button. Here, PageButton is used as this reference. Once the button is created, its properties can be assigned. Its Text property is set to the loop index i to provide a label showing the page number. It is given an id property by appending the loop index to the character "P", creating buttons P1, P2, P3, P4, and P5. There is nothing significant about the id; it is simply a unique identifier for the button. The button's CommandArgument property is now set to a string composed of the beginning (StartKey) and ending (EndKey) item numbers determined for this button, concatenated with the separator character "|". This, finally, is what all the previous work was about. The button is also style with a width and background color so that all buttons have the same size and appearance.

63 Display Records w/Paging To be activated, a button needs an event handler. It is supplied with an (on) Command handler to call the DisplayRepeater subroutine. AddHandler PageButton.Command, AddressOf DisplayRepeater An AddHandler statement is in the general format: AddHandler object.event, AddressOf subprogram The Visual Basic AddHandler procedure adds a named event handler to an object, specifying the AddressOf subroutine to call when the event handler is invoked. With the button fully defined it is added to the placeholder created earlier as the location for paging buttons: PageButtons.Controls.Add(PageButton) The button is added to the placeholder's Controls collection through the collection's Add() method as: controlscollection.Add(object) In this case a new PageButton object is added to the PageButtons.Controls collection. When the processing loop finishes, the full complement of buttons will have been added to the placeholder and appear on the page.

64 Display Records w/Paging Displaying the Repeater: The paging buttons call the DisplayRepeater subroutine to retrieve and display the subset of product records indicated in their CommandName property. The subprogram needs to access this property, parse the beginning and ending item numbers from the string, and display those records. The signature of the following subprogram requires a call from a command button.

65 Display Records w/Paging Sub DisplayRepeater (Src As Object, Args As CommandEventArgs) Dim Keys() As String Keys = Split(Args.CommandName, "|") '-- Bind the Repeater DBConnection = New OleDbConnection( _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=d:\Databases\eCommerce.mdb") DBConnection.Open() SQLString = "SELECT * FROM Products WHERE " & _ "ItemNumber >= '" & Keys(0) & "' AND " & _ "ItemNumber <= '" & Keys(1) & "' "ORDER BY ItemNumber“ DBCommand = New OleDbCommand(SQLString, DBConnection) DBReader = DBCommand.ExecuteReader() RepeaterDisplay.DataSource = DBReader RepeaterDisplay.DataBind() DBReader.Close() DBConnection.Close()

66 Display Records w/Paging '-- Highlight clicked button Dim Item As Button Dim ThisButton As Button For Each Item in PageButtons.Controls ThisButton = CType(Item, Button) ThisButton.Style("background-color") = "#F0F0F0“ ThisButton.Style("color") = "#000000" Next ThisButton = CType(PageButtons.FindControl(Src.id), _ Button) ThisButton.Style("background-color") = "#990000“ ThisButton.Style("color") = "#FFFFFF" End Sub

67 Display Records w/Paging Extraction of the item numbers from the passed CommandArgument uses the Visual Basic Split() statement to parse the string Args.CommandArgument into elements of array Keys, splitting the string at the "|" character. As a result, the beginning item number is in Keys(0) and the ending item number is in Keys(1). Other string methods could be used, but the Split() method is automatic and easy. Now, an appropriate SQL statement can be composed to retrieve these records: Taking the first button as an example, the SQL statement becomes: SELECT * FROM Products WHERE _ ItemNumber >= 'BU1111' AND _ ItemNumber <= 'DB1111' The statement is issued against the Products table and four records are retrieved and bound to the Repeater.

68 Display Records w/Paging Finding Scripted Controls: The last statements in the subprogram highlight the clicked button for visual emphasis, changing its background and text colors. First, though, the previously highlighted button needs to be un-highlighted. The script loops through the placeholder's Controls collection (PageButtons.Controls) converting each control to a button object (CType(Item, Button)) and setting its background and foreground colors to normal. Dim Item As Button Dim ThisButton As Button For Each Item in PageButtons.Controls ThisButton = CType(Item, Button) ThisButton.Style("background-color") = "#F0F0F0“ ThisButton.Style("color") = "#000000" Next

69 Display Records w/Paging The button that is clicked needs to be found among the several buttons appearing in the placeholder so that its background and foreground colors can be set. To locate script-generated controls on a page the FindControl() method of the Controls collection is used. Its general format is shown below: controlscollection.FindControl("id")

70 Display Records w/Paging The identify of the button that is clicked is given by the Src.id argument passed to the subprogram when it is called. Therefore, the PageButtons collection is searched to locate this control and to convert it to a button object. Then its background and foreground colors can be set. As one final touch, the first button in the group should be highlighted when the page first loads and the Repeater displays the first subset of records. Therefore, a routine to do this is added at the end of the Page_Load script.

71 Display Records w/Paging Sub Page_Load If Not Page.IsPostBack Then...display initial Repeater End If...create paging buttons If Not Page.IsPostBack Then Dim FirstButton As Button FirstButton = CType(PageButtons.FindControl("P1"), Button) FirstButton.Style("background-color") = "#990000“ FirstButton.Style("color") = "#FFFFFF" End If End Sub

72 Display Records w/Paging The first button has id="P1" because of the naming convention chosen, so this is the control that is found and styled. Note that is routine is not part of the previous If Not Page.IsPostBack routine within which the Repeater is initially displayed. This first button cannot be highlighted until after the Page_Load script finishes creating all the buttons. You can, though, package the Repeater display and this routine together as long as they both appear last in the Page_Load script. As mentioned previously, the paging techniques presented here are adaptable to any of the information display controls -- asp:Repeater, asp:DataGrid, and asp:DataList. The reason these paging buttons can be used for any of the controls is that they are not part of the controls themselves. They reside separately inside an asp:PlaceHolder control that can be displayed along side any of the information display controls. Also, when applied to other database tables, the range of keys associated with the buttons can be easily determined from the values in the data field used to identify subsets of records. PagedRepeater.aspx

73 Adding Records Records are added to a database table through a form presenting input areas for entering the fields of information. A button then calls a subroutine to write the new information to the table with an SQL INSERT command.

74 Add Form An add form is formatted in a table with server controls for data input areas. With the exception of the asp:DropDownList control for the ItemType field, all controls are asp:TextBox controls. Associated with these input controls are asp:Label controls for displaying error messages resulting from data entry problems. These message areas have their EnableViewState properties set to "False" to keep previous messages from reappearing on form postings.

75 Add Form Product Add Item Number: <asp:TextBox id="ItemNumber" runat="server" _ Columns="6“ MaxLength="6"/> <asp:Label id="ItemNumberMessage" runat="server" _ ForeColor="#FF0000" EnableViewState="False"/> Item Type:

76 Add Form Item Supplier: <asp:TextBox id="ItemSupplier" runat="server" _ Columns="40" MaxLength="50"/> <asp:Label id="ItemSupplierMessage" runat="server" _ ForeColor="#FF0000" EnableViewState="False"/> Item Name: <asp:TextBox id="ItemName" runat="server" _ Columns="40" MaxLength="50"/> <asp:Label id="ItemNameMessage" runat="server" _ ForeColor="#FF0000" EnableViewState="False"/> Item Description: <asp:TextBox id="ItemDescription" runat="server" _ TextMode="MultiLine" Columns="45" rows="3"/> <asp:Label id="ItemDescriptionMessage" runat="server" _ ForeColor="#FF0000" EnableViewState="False"/>

77 Add Form Item Price: $ <asp:TextBox id="ItemPrice" runat="server" _ Columns="7" MaxLength="6"/> <asp:Label id="ItemPriceMessage" runat="server" _ ForeColor="#FF0000" EnableViewState="False"/> Item Quantity: <asp:TextBox id="ItemQuantity" runat="server" _ Columns="3" MaxLength="3"/> <asp:Label id="ItemQuantityMessage" runat="server" _ ForeColor="#FF0000" EnableViewState="False"/>

78 Add Form <asp:Button Text="Add Record" _ OnClick="AddRecord" runat="server"/> <asp:Button Text="Clear Form" _ OnClick="ClearForm" runat="server"/> <asp:Label id="AddRecordMessage" _ runat="server" ForeColor="#FF0000" _ EnableViewState="False"/>

79 Add Form When defining text input areas for data to be written to a database, it is particularly important that the length of the entered data does not exceed the size of the field in the database. This mismatch in field sizes causes execution errors. Therefore, all of the asp:TextBox controls which have restricted sizes in the database have their MaxLength sizes set to the size of the field in the database table so that no more than this number of characters can be entered.

80 Loading the Product Types The product type input field is an asp:DropDownList supplying the valid product types (one way of reducing the possibility of input errors). This list is created when the page is first loaded by populating the control with ItemType values from the Products table.

81 Loading the Product Types Sub Page_Load If Not Page.IsPostBack Then '-- Load drop-down list with item types DBConnection = New OleDbConnection( _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=d:\Databases\eCommerce.mdb") DBConnection.Open() SQLString = "SELECT DISTINCT ItemType FROM Products _ ORDER BY ItemType" DBCommand = New OleDbCommand(SQLString, DBConnection) DBReader = DBCommand.ExecuteReader() ItemType.DataSource = DBReader ItemType.DataTextField = "ItemType" ItemType.DataValueField = "ItemType" ItemType.DataBind() DBReader.Close() DBConnection.Close() End If End Sub

82 Checking Entered Data When the "Add Record" button is clicked, the AddRecord subroutine is called to add the entered data as a new record in the Products table. Before writing a record, though, the entered data needs to be validated as best possible. The first part of the AddRecord subroutine puts the entered data through a series of editing checks.

83 Checking Entered Data Sub AddRecord (Src As Object, Args As EventArgs) '-- CHECK FOR VALID RECORD --- Dim ValidRecord As Boolean = True '-- Check for valid ItemNumber If Len(ItemNumber.Text) <> 6 Then ItemNumberMessage.Text = "Invalid Item Number length" ValidRecord = False ElseIf Not IsNumeric(Right(ItemNumber.Text,4)) Then ItemNumberMessage.Text = "Invalid Item Number format" ValidRecord = False Else ItemNumber.Text = UCase(ItemNumber.Text) End If

84 Checking Entered Data '-- Check for missing Item Supplier If ItemSupplier.Text = "" Then ItemSupplierMessage.Text = "Missing Item Supplier" ValidRecord = False End If '-- Check for missing Item Name If ItemName.Text = "" Then ItemNameMessage.Text = "Missing Item Name" ValidRecord = False End If '-- Check for missing Item Description If ItemDescription.Text = "" Then ItemDescriptionMessage.Text = "Missing Item Description" ValidRecord = False End If

85 Checking Entered Data '-- Check for valid Item Price If Not IsNumeric(ItemPrice.Text) Then ItemPriceMessage.Text = "Invalid Item Price format" ValidRecord = False End If '-- Check for valid Item Quantity If Not IsNumeric(ItemQuantity.Text) Then ItemQuantityMessage.Text = "Invalid Item Quantity format" ValidRecord = False End If If ValidRecord = True Then...continue... End If End Sub

86 Checking Entered Data An edit flag -- variable ValidRecord -- is initialized as True, and at the end of the editing routines indicates whether or not an error was discovered in the entered data. If its value remains True, the script can continue the process of adding the new record to the table. The editing routines look for missing data in a field, a sufficient number of characters in the field, or, in the case of the price and quantity fields, numeric characters only. If an error is discovered, ValidRecord is set to False and an appropriate error message is written to the message label accompanying the field.

87 Checking for an Existing Record If the entered data passes all the editing checks, it is still necessary to make sure that the record being added does not have the same ItemNumber value as an existing record in the table. The ItemNumber is the unique record "key," and duplicates are not allowed.

88 Checking for an Existing Record If ValidRecord = True Then '--- CHECK FOR DUPLICATE RECORD --- DBConnection = New OleDbConnection( _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=d:\Databases\eCommerce.mdb") DBConnection.Open() SQLString = "SELECT Count(*) FROM Products " & _ WHERE ItemNumber = '" & ItemNumber.Text & "'" DBCommand = New OleDbCommand(SQLString, DBConnection) If DBCommand.ExecuteScalar() <> 0 Then AddRecordMessage.Text = "Duplicate Item Number. Record _ not added." ValidRecord = False End If DBConnection.Close() End If

89 Checking for an Existing Record A check for a duplicate record is made by getting a count of the number of records in the table with the same ItemNumber as was entered in the data entry form. The following SQL statement is issued against the database: "SELECT Count(*) FROM Products _ WHERE ItemNumber = '" & _ ItemNumber.Text & "'"

90 The ExecuteScalar() Method To return a count of matching records the ExecuteScalar() method of the Command object is used. This method is used when returning a single value from an SQL query rather than a recordset requiring a data reader. In this case the single returned value is a count of the number of records matching the input item number that can be assigned to a variable and tested: Dim RecordCount As Integer RecordCount = DBCommand.ExecuteScalar() If RecordCount <> 0 Then AddRecordMessage.Text = "Duplicate Item _ Number. Record not added." ValidRecord = False End If

91 Adding a Table Record If all editing checks are passed and there is not a duplicate record in the Products table, then the new record can be added to the table. The database access script is placed inside a Try...Catch structure to trap for any remaining errors that could cause script execution problems.

92 Adding a Table Record '-- ADD A NEW RECORD – Try DBConnection = New OleDbConnection( _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=d:\Databases\eCommerce.mdb") DBConnection.Open() SQLString = "INSERT INTO Products " & _ "(ItemNumber, ItemType, ItemSupplier, ItemName, " & _ "ItemDescription, ItemPrice, ItemQuantity) " & _ "VALUES (" & "'" & ItemNumber.Text & "', " & _ "'" & ItemType.SelectedItem.Value & "', " & _ "'" & Replace(ItemSupplier.Text, "'", "''") & "', " & _ "'" & Replace(ItemName.Text, "'", "''") & "', " & _ "'" & Replace(ItemDescription.Text, "'", "''") & "', " & _ ItemPrice.Text & ", " & ItemQuantity.Text & ")"

93 Adding a Table Record DBCommand = New OleDbCommand(SQLString, DBConnection) DBCommand.ExecuteNonQuery DBConnection.Close() AddMessage.Text = "Record added“ Catch AddMessage.Text = "Update problem. _ Record not added. " & SQLString End Try

94 Adding a Table Record The entered data values are inserted into the table with an SQL INSERT statement. An example of the format of this statement when data values are added is: INSERT INTO Products (ItemNumber, _ ItemType, ItemSupplier, ItemName, _ ItemDescription, ItemPrice, ItemQuantity) _ VALUES ('BU5555', 'Business Office', _ 'Microsoft', 'Visio', 'Description of product...', _ 399.99, 10)

95 Adding a Table Record The SQL statement is composed by concatenating literal text and input values, making sure to surround string values with single quotes (apostrophes) and to separate values with commas. For instance, the input item number is concatenated to the statement with: "'" & ItemNumber.Text & "', "

96 Adding a Table Record A single quote is concatenated with the input value and with a closing single quote to produce, say, 'BU5555' as the value to be written to the ItemNumber field of the database. Whether a string or numeric value is formatted depends on the field type in the database.

97 Replacing Apostrophes in Text Fields Text fields can, themselves, contain apostrophes. For instance, the ItemSupplier, ItemName, and ItemDescription fields may contain apostrophes as part of their data values. When this occurs, it causes a syntax error in the SQL statement. For example, if the name of the supplier is Software 'R Us, then this value portion of the SQL statement becomes: 'Software 'R Us'

98 Replacing Apostrophes in Text Fields There are too many apostrophes. It is necessary to convert the single enclosed apostrophe to two apostrophes to handle the problem. The Visual Basic Replace statement accomplishes this replacement: "'" & Replace(ItemSupplier.Text, "'", "''") & "'“ resulting in the SQL value 'Software ''R Us' and all is well. Any time a text field may contain an apostrophe as part of its data value, make sure to replace single with double apostrophes.

99 The ExecuteNonQuery() Method Once the SQL statement is constructed, it is issued through the Command object using the ExecuteNonQuery() method. This method is used when there are no records returned by the SQL statement and no requirement for a data reader. The Command.ExecuteNonQuery() method is also used for issuing SQL DELETE and UPDATE statements. After the record is added to the table, a confirmation message is written to the AddMessage label.

100 Clearing the Form Since the input form takes part in the page's View State, entered values are echoed back and reappear when the form is submitted. This makes it convenient to correct input errors in individual fields since the entire form does not have to be re-entered every time an error is made. However, once the data are written to the database the expectation is to add another record. In this case there is inconvenience in having to edit each of the input areas to enter new data. A means is needed to clear the entire form. The "Clear Form" button accomplishes this clearing of current data values to produce a blank form. The button calls the ClearForm subprogram, which writes null values to the form fields.

101 Clearing the Form Sub ClearForm (Src As Object, Args As EventArgs) ItemNumber.Text = "" ItemSupplier.Text = "" ItemName.Text = "" ItemDescription.Text = "" ItemPrice.Text = "" ItemQuantity.Text = "" End Sub Of course, the ItemType DropDownList is not cleared since these entries need to remain accessible for the next new record. AddRecord.aspx

102 Deleting Records Records are removed from a database table by identifying a record and issuing an SQL command to delete the chosen record. In the Products table, records are identified by their unique ItemNumber values. This is the field used to choose a record for deletion. Often, the record is retrieved and displayed for visual verification prior to deletion.

103 The Delete Form In the present example, a form presents a drop-down list of ItemNumbers from which to choose the particular record to delete. After that selection is made, all of the fields of that record are displayed for verification along with a "Delete Record" button. Clicking the button deletes the record from the Products table. The delete form is formatted in a table with server controls for data display areas. With the exception of the asp:DropDownList control for the ItemNumber field, all controls are asp:TextBox controls with ReadOnly="True" properties. This property does not permit editing of the fields, although no harm is done in doing so.

104 The Delete Form Product Delete Item Number: <asp:Label id="DeleteMessage" runat="server“ _ EnableViewState="False" ForeColor="#FF0000"/> Item Type: <asp:TextBox id="ItemType" runat="server" _ Columns="20" ReadOnly="True"/>

105 The Delete Form Item Supplier: <asp:TextBox id="ItemSupplier" runat="server" _ Columns="50" ReadOnly="True"/> Item Name: <asp:TextBox id="ItemName" runat="server" _ Columns="50" ReadOnly="True"/> Item Description: <asp:TextBox id="ItemDescription" runat="server" _ TextMode="MultiLine" Columns="55" rows="3" ReadOnly="True"/>

106 The Delete Form Item Price: $ <asp:TextBox id="ItemPrice" runat="server" _ Columns="7" ReadOnly="True"/> Item Quantity: <asp:TextBox id="ItemQuantity" runat="server" _ Columns="3" ReadOnly="True"/>

107 The Delete Form <asp:Button id="DeleteButton" runat="server" _ Text="Delete Record" Visible="False" _ OnClick="DeleteRecord"/>

108 The Delete Form All table rows except for the first one (displaying the drop-down list of ItemNumbers) are enclosed inside an asp:Panel control with Visible="False". These display rows are hidden until an ItemNumber is selected from the list. Also, the DeleteButton control below the table is hidden until an ItemNumber is chosen. An asp:Label control appears along side the "Select" button for display of a record deletion confirmation message.

109 Creating the ItemNumber List The asp:DropDownList of item numbers is created when the page is loaded. It is built from the ItemNumber field in the Products table. Creation of the drop-down list is encapsulated in the CreateItemNumberDropDown subprogram rather than being coded directly in the Page_Load routine because the list needs to be built on two separate occasions. It is created when the page is initially loaded, and it is recreated when a record is deleted.

110 Creating the ItemNumber List When a record is deleted from the Products table the drop-down list needs to be repopulated from scratch. The View State retains the item number of the deleted record in the drop-down list. However, the drop-down list should not include this item number. So, the list is rebuilt by calling CreateItemNumberDropDown after a record is deleted. The list is rebuilt by first clearing its contents of existing items with ItemNumbers.Items.Clear(). This is a call to the Clear() method of the Items collection of the ItemNumbers list control. Then a new collection of item numbers is retrieved from the Products table and bound to the ItemNumbers DropDownList.

111 Creating the ItemNumber List Sub Page_Load If Not Page.IsPostBack Then CreateItemNumberDropDown End If End Sub Sub CreateItemNumberDropDown ItemNumbers.Items.Clear() DBConnection = New OleDbConnection( _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=d:\Databases\eCommerce.mdb") DBConnection.Open() SQLString = "SELECT ItemNumber FROM Products _ ORDER BY ItemNumber"

112 Creating the ItemNumber List DBCommand = New OleDbCommand(SQLString, DBConnection) DBReader = DBCommand.ExecuteReader() ItemNumbers.DataSource = DBReader ItemNumbers.DataTextField = "ItemNumber" ItemNumbers.DataValueField = "ItemNumber" ItemNumbers.DataBind() DBReader.Close() DBConnection.Close() End Sub

113 Selecting a Record for Deletion When the "Select" button is clicked, the SelectRecord subroutine is called to retrieve and display the record for visual verification that this is, indeed, the record to be deleted. The selected record is retrieved by locating the one whose ItemNumber matches the one choses from the drop-down list (ItemNumbers.SelectedItem.Value). This single record is retrieved and used to populate the text boxes in the display form. Then, the hidden panel of table rows is made visible along with the delete button.

114 Selecting a Record for Deletion Sub SelectRecord (Src As Object, Args As EventArgs) DBConnection = New OleDbConnection( _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=d:\Databases\eCommerce.mdb") DBConnection.Open() SQLString = "SELECT * FROM Products " & _ "WHERE ItemNumber = '" & ItemNumbers.SelectedItem.Value & "'" DBCommand = New OleDbCommand(SQLString, DBConnection) DBReader = DBCommand.ExecuteReader() DBReader.Read()

115 Selecting a Record for Deletion ItemType.Text = DBReader("ItemType") ItemSupplier.Text = DBReader("ItemSupplier") ItemName.Text = DBReader("ItemName") ItemDescription.Text = DBReader("ItemDescription") ItemPrice.Text = DBReader("ItemPrice") ItemQuantity.Text = DBReader("ItemQuantity") DBReader.Close() DBConnection.Close() DeletePanel.Visible = True DeleteButton.Visible = True End Sub

116 Deleting a Record A click on the "Delete Record" button calls the DeleteRecord subroutine. An SQL DELETE statement is composed to delete the record whose ItemNumber matches the one selected from the drop-down list. The statement is issued through the Command object's ExecuteNonQuery() method since no records are returned from the query. Once the record is deleted, the display fields and delete button are made invisible again and a confirmation message is displayed in the DeleteMessage Label control. Importantly, the drop- down list is rebuilt by calling the CreateItemNumberDropDown subroutine. Doing so ensures that the just-deleted record's item number will not reappear in the drop-down list.

117 Deleting a Record Sub DeleteRecord (Src As Object, Args As EventArgs) DBConnection = New OleDbConnection( _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=d:\Databases\eCommerce.mdb") DBConnection.Open() SQLString = "DELETE FROM Products " & _ "WHERE ItemNumber = '" & ItemNumbers.SelectedItem.Value & "'" DBCommand = New OleDbCommand(SQLString, DBConnection) DBCommand.ExecuteNonQuery() DBConnection.Close() DeletePanel.Visible = False DeleteButton.Visible = False DeleteMessage.Text = "Record " & _ ItemNumbers.SelectedItem.Value & " deleted" CreateItemNumberDropDown DeleteRecord.aspx

118 Updating Records in a Table Records are updated in a database table by selecting a record, changing data values in the fields, and issuing an SQL command to rewrite the changed record to the table. Coding for the update page combines many of the techniques used for adding and deleting records. The update form is set up much like the add form with text boxes for revising data values and with associated error message areas formatted as labels. As with the add form, changed values require data entry editing.

119 The Update Form A form presents a drop-down list of ItemNumbers from which to choose the particular record to update. After the selection is made all of the fields of that record are extracted from the Products table and displayed along with an "Update Record" button. Clicking the button rewrites the record with any changes made to the fields.

120 The Update Form Item Number: <asp:Button Text="Select" OnClick="SelectRecord" _ runat="server"/> Item Type:

121 The Update Form All table rows except for the drop-down list of ItemNumbers are enclosed inside an asp:Panel control with Visible="False". These display rows are hidden until an ItemNumber is selected from the list. Also, the UpdateButton control below the table is hidden until an ItemNumber is chosen. An asp:Label control appears along side the "Update" button for display of a record update confirmation message.

122 Loading the Drop-Down Lists On page load the drop-down list of item numbers is created. Selecting a number from this list displays the full form for record editing. The drop-down list of item types is also loaded. Although this list is not displayed until a record is chosen for editing it needs to be loaded only once; its values are retained in View State between page postings.

123 Selecting and Displaying a Record for Updating When the "Select" button is clicked the SelectRecord subprogram is called to retrieve and display the current record. The form is made visible for editing. Text fields are populated from the Products table by assigning current values from the retrieved record. Displaying the current value of the ItemType requires that the matching value be selected in the drop-down list.

124 Selecting and Displaying a Record for Updating SQLString = "SELECT * FROM Products WHERE " & _ "ItemNumber = '" & ItemNumbers.SelectedItem.Value & "'" Dim i As Integer For i = 0 To ItemType.Items.Count - 1 ItemType.Items(i).Selected = False If ItemType.Items(i).Value = DBReader("ItemType") Then ItemType.Items(i).Selected = True End If Next ItemSupplier.Text = DBReader("ItemSupplier")...

125 Selecting and Displaying a Record for Updating An item in a drop-down list is selected for display by setting its Selected property to True. At the same time the Selected property of a previously displayed record must be set to False, otherwise an error results from having two different items selected. The script iterates the Items collection setting all Selected properties to False; the item whose value matches the value in the current record has its Selected property set to True.

126 Updating a Record A click on the "Update Record" button calls the UpdateRecord subprogram. As is the case for adding a record, changed fields require editing to ensure that only valid data are rewritten to the table. Updating is performed with the SQL UPDATE statement issued through the Command object's ExecuteNonQuery() method. No recordset is returned from the query. With all the literals and inserted values in place the UPDATE statement resembles the following example: UPDATE Products SET ItemType='Business Office', _ ItemSupplier='Microsoft', ItemName='Office 2003 Professional', _ ItemDescription='...description...', ItemPrice=459.75, _ ItemQuantity=25 WHERE ItemNumber='BU1111'

127 Updating a Record Update statements are enclosed within a Try...Catch structure to trap any rewrite errors. When updating is complete a confirmation message is displayed. The ItemNumber field is not updated. This is the record "key" and no change in this value is permitted. If the value were inadvertently changed then the wrong record would be updated. Changing the key field is akin to adding a new record to the table. To change an item number, delete the existing record with this key and add an entirely new record. UpdateRecord.aspx


Download ppt "ASP.NET Database Operations. Sorting with Repeater For this example, records from the Products table are sorted prior to their display in the Repeater."

Similar presentations


Ads by Google