CIS Logo SVC Logo

   Computing & Information Systems
   Department

 

Schoology Facebook        Search CIS Site      Tutorials

Cars App 1



What's the Plan?


The plan is to create a web app similar to e-commerce app 2, but to adapt it for an online store selling made-to-order cars from various manufacturers. The main feature that is added is the grouping of products (cars) by departments (brands, manufacturers, categories, or whatever you wish to call this). Thus, a customer would typically select a brand of car from a drop-down list and then select a particular model of car from the drop-down list that appears as a result of the choice of brand. Selecting the model brings up a page of detailed information on the product (car).

Since our business builds cars as the orders arrive, there is no inventory of cars to keep track of. In other e-commerce applications, tracking inventory and letting customers see if a product is in stock or not might be needed. Inventory information might be kept in its own table or might be a column in the Product table.

The search functionality in this app can also be used to look up cars matching a certain target string. This search functionality is expanded so that the matches for the target string are sought in substrings of the product name (car model), product brand name (manufacturer), and product description. The brand name is the new item here.
  • The home page is shown in this screen shot.
  • The privacy page and contact page are much the same as we used before.
  • The brands page allows the user to choose from a pull-down list the brands (manufacturers) of cars.
  • Doing so brings up the cars page, which allows the user to choose a particular model of car from a pull-down list.
  • That then brings up the results page, which shows the details about that particular car, such as the description and price.
  • The search page is similar to what we used before.
  • After entering a search string at the search page, the search results page is shown.
  • Clicking on the 2 link at the bottom brings up the second page of search results.
  • Clicking on one of the View buttons on the search results page takes you to the same results page already seen above.

Copying Existing Pages

  • Although you can build this project from scratch, it is easier to start with some pre-built pages. To do so, copy the Template folder from the VB folder of the CS 305 course network drive or unzip the contents of template.zip.
  • Open the project in Visual Studio 2005.
  • Copy into your Web.config file the connectionStrings section from one of your previous e-commerce or database web apps, overwriting the <connectionStrings/> tag that was there.
  • Check that Server Explorer now allows you to expand that connection so as to see your tables and stored procedures. If not, see your instructor.
  • The copied pages have no code in their VB files, so we will add the needed code below.
  • Also, note that the various web forms are content pages that all use the same master page.

Database Tables



Product Table

  • In Server Explorer we create 3 tables as follows.
  • We begin with a Product table:
Column Name Data Type Allow Nulls
ProdNum int no
ProdName varchar(24) no
ProdDescription varchar(128) yes
ProdPrice money no

  • In addition, make ProdNum to be the primary key field (by right clicking in the margin in front of this row and selected Set Primary Key).
  • Also make it an Identity field (by setting the Is Identity property to Yes).
  • Do File, Save and while saving, give Product as the name of the table.
  • Add the following data to this table. Do not type the ProdNum values as these are autogenerated since ProdNum is an Identity field.
ProdNum ProdName ProdDescription ProdPrice
1 Hurricane Top of line luxury automobile. GPS navigation system comes standard. 35255
2 Tornado Top of line sports car. 32999
3 Cheetah Modestly-priced sports car. 27880
4 Famtastic Modestly-priced family car. 22555
5 Lightning Sporty two-seater electric/gas hybrid car. 33000
6 Bolt Small 4-seater electric/gas hybrid car. 36500
7 Thunder Large 6-seater electric/gas hybrid car. 39999
8 Rocket Our fastest sports car. 38400
9 Laser Small 2-seater sports car. 37600
10 Kangaroo Large all terrain vehicle. 35000
11 Rabbit Small all terrain vehicle. 33900
12 M-star Medium-sized sport utility vehicle. 29000
13 Roady Modestly-priced sports car. 28100
14 Hippo Large sport utility vehicle. 31200

Category Table

  • Next, we wish to create a table called Category to hold the product categories (brands or manufacturers if you prefer that terminology).
  • Use the following design:
Column Name Data Type Allow Nulls
CategoryNum int no
CategoryName varchar(24) no

  • In addition, make CategoryNum to be the primary key field.
  • Also make it an Identity field.
  • Do File, Save and while saving, give Category as the name of the table.
  • Add the following data to this table. Do not type the CategoryNum values as these are autogenerated since CategoryNum is an Identity field.
CategoryNum CategoryName
1 Electra Motors
2 Alpha Omega
3 Vanguard
4 Road Master

CategoryProduct Table

  • Next, we want to create a table called CategoryProduct to link the Category and Product tables.
  • Use the following design:
Column Name Data Type Allow Nulls
CategoryNum int no
ProdNum int no

  • In addition, make CategoryNum and ProdNum to be the composite primary key field.
  • To do this, click on the margin in front of the first row. Then use CTRL right click on the margin in front of the second row.
  • Choose Set Primary Key. If successful, the key icon will show up in front of both rows.
  • The primary key is then the combination of these 2 fields.
  • Do File, Save and while saving, give CategoryProduct as the name of the table.
  • Add the following data to this table:
CategoryNum ProdNum
1 5
1 6
1 7
2 8
2 9
2 10
2 11
3 1
3 2
3 3
3 4
4 12
4 13
4 14

Relationships Between Tables

  • We should set up the appropriate relationships between the CategoryProduct table and each of the other two tables.
  • Right click on the CategoryProduct table and select Open Table Definition.
  • Select Table Designer, Relationships (or just click the Relationships button).
  • We wish to set up a relationship between the ProdNum (primary key) field of the Product table and the ProdNum (foreign key) field of the CategoryProduct table.
  • In the Foreign Key Relationships dialog box that you should now have, click the Add button. Some default name will be given to this new relationship, but it will be adjusted automatically once you select the primary key table (in the next few steps). The name will end up as FK_CategoryProduct_Product, but there is no need to manually adjust the name.
  • Click in the field to the right of Tables and Columns Specification. You will then see a "..." button. Click on it.
  • This presents us with a Tables and Columns dialog box which we want to adjust to look like this screen shot.
  • Begin by selecting Product as the Primary key table. Under it you want the ProdNum field to be the only one listed. If there are other fields shown, click in its box and use the pull-down to change the entry to None. That will clear out the unwanted value.
  • The Foreign key table should automatically be listed as CategoryProduct. Adjust things so that the only field listed under this is ProdNum. It should be in the same line as ProdNum for the Product table.
  • Click OK, which takes you back to the properties dialog for this relationship. Make sure that the following 3 properties are marked as Yes: Check Existing Data on Creation or Re-Enabling, Enforce for Replication, and Enforce Foreign Key Constraint. They will probably be set this way by default.
  • Then click the Add button to start setting up a second relationship. This time we want to set up a relationship between the CategoryNum (primary key) field of the Category table and the CategoryNum (foreign key) field of the CategoryProduct table.
  • Click in the field to the right of Tables and Columns Specification. You will then see a "..." button. Click on it.
  • This again presents us with a Tables and Columns dialog box which we want to adjust to look like this screen shot.
  • Select Category as the Primary key table. Under it you want the CategoryNum field to be the only one listed. Remove any others.
  • The Foreign key table should automatically be listed as CategoryProduct. Adjust things so that the only field listed under this is CategoryNum. It should be in the same line as CategoryNum for the Category table.
  • Click OK, which takes you back to the properties dialog for this relationship. Make sure that the following 3 properties are marked as Yes: Check Existing Data on Creation or Re-Enabling, Enforce for Replication, and Enforce Foreign Key Constraint.
  • Click on Close in the dialog box as we are done creating the needed relationships between the tables.
  • Then do File, Save to save the changes to these tables. You can then close the Table Definition window.

Stored Procedures and VB Code



Stored Procedure for Brands Page

  • The code-behind file for this page needs a stored procedure to retrieve the brand names so that we can display them in the drop-down list.
  • In Server Explorer, right click on Stored Procedures and select Add New Stored Procedure.
  • Adjust the resulting outline of a stored procedure to match the following.

CREATE PROCEDURE db_datareader.SelectCategoryName 
AS
    SET NOCOUNT ON
    SELECT CategoryName FROM Category ORDER BY CategoryName
    RETURN

  • The stored procedure simply returns the CategoryName column from the Category table and puts the results in ascending order.
  • Save your stored procedure.
  • Right click on your stored procedure and select execute. Make sure that it returns reasonable data.
  • Of course, save all of your files now and periodically throughout the development of this web app.

Brands Code-Behind File

  • Open the Brands.aspx.vb code-behind file.
  • Adjust the code to match that shown below, except that you must change the name of the connection string from "PartsConnectionString" to whatever is used for your connection in your Web.config file.
  • Make the same change in all places in this project where you set up to connect to your database.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim TargetBrand As String

    If Not IsPostBack Then
        Dim myDatabaseConnection As SqlClient.SqlConnection = Nothing
        Dim myCommand As SqlClient.SqlCommand = Nothing
        Dim myReader As SqlClient.SqlDataReader = Nothing

        Try
            Dim connectionString As String = _
                ConfigurationManager.ConnectionStrings("PartsConnectionString").ConnectionString
            myDatabaseConnection = New SqlClient.SqlConnection(connectionString)
            myCommand = New SqlClient.SqlCommand()
            BrandList.Items.Add("*** Make a choice ***")

            'Set up to use a stored procedure:
            myCommand.CommandType = CommandType.StoredProcedure
            myCommand.Connection = myDatabaseConnection
            myCommand.CommandText = "SelectCategoryName"

            'Use an SqlDataReader to execute the stored procedure and
            'get the results into the drop down list:
            myDatabaseConnection.Open()
            myReader = myCommand.ExecuteReader()
            While (myReader.Read())
                BrandList.Items.Add(myReader.GetString(0))
            End While

            myDatabaseConnection.Close()
            myDatabaseConnection.Dispose()
        Catch exception As System.Data.SqlClient.SqlException
            ErrorLabel.Visible = True
        Catch exception As Exception
            ErrorLabel.Visible = True
        Finally    'Do cleanup tasks here:
            myCommand = Nothing

            If Not myReader Is Nothing AndAlso _
                Not myReader.IsClosed Then
                myReader.Close()
            End If

            myReader = Nothing

            If Not myDatabaseConnection Is Nothing AndAlso _
                myDatabaseConnection.State = ConnectionState.Open Then
                myDatabaseConnection.Close()
                myDatabaseConnection.Dispose()
            End If

            myDatabaseConnection = Nothing
        End Try
    Else   ' We have a postback.
        TargetBrand = BrandList.SelectedItem.Text
        Session.Add("BrandSelected", TargetBrand)
        Response.Redirect("Cars.aspx")
    End If
End Sub

  • As you can see, the above code calls upon our stored procedure to obtain the brand names (categories), then uses a data reader to read each one and stick it into our drop-down list.
  • Since the drop-down list's autopostback property is set to True, when the user selects one of the brands, a postback occurs.
  • In the case of a postback, the selected brand name is stored in session state, and the web app redirects to the Cars page.

Stored Procedure for Cars Page

  • We set up a stored procedure called SelectProdName. The stored procedure returns the ProdName field from the Product table and the CategoryName field from the Category table for all rows of the joined table where the @TargetBrand parameter matches the CategoryName. This is because we want to get a list of the names of the products (cars) for the selected category (brand). We will put this list of product names into the drop-down list on the cars page. We also order this data by ProdName.
  • Add a new stored procedure and adjust it to look like this:

CREATE PROCEDURE db_datareader.SelectProdName 
(
    @TargetBrand varchar(24)
)
AS
    SET NOCOUNT ON
    SELECT Product.ProdName, Category.CategoryName
FROM Product INNER JOIN CategoryProduct 
ON Product.ProdNum = CategoryProduct.ProdNum
INNER JOIN Category ON CategoryProduct.CategoryNum = Category.CategoryNum
WHERE (Category.CategoryName = @TargetBrand)
ORDER BY Product.ProdName
    RETURN

  • As usual save your stored procedure and execute it. When executing the stored procedure, you will have to supply a value for the @TargetBrand parameter. Use Vanguard or one of the other brand names (categories). Make sure that the stored procedure returns the names of the models for this brand.

Cars Code-Behind File

  • In the Cars.apsx.vb code-behind file we set up the BrandLabel so that it displays the brand name already chosen (and available here because we saved it in the session state).
  • We also pass this brand name as the parameter to the stored procedure so that it can look up the names of all the car models for this manufacturer (brand). These model names are then used to populate the CarList drop-down list.
  • If the user selects an item from the list (other than the "*** Make a choice ***" string) we add the selected model name to the session state and redirect to the Results.aspx page.
  • The complete code for the Page_Load procedure should look like this:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim TargetModel As String

    If Not IsPostBack Then
        Dim myDatabaseConnection As SqlClient.SqlConnection = Nothing
        Dim myCommand As SqlClient.SqlCommand = Nothing
        Dim myReader As SqlClient.SqlDataReader = Nothing

        Try
            Dim connectionString As String = _
                ConfigurationManager.ConnectionStrings("PartsConnectionString").ConnectionString
            myDatabaseConnection = New SqlClient.SqlConnection(connectionString)
            myCommand = New SqlClient.SqlCommand()
            BrandLabel.Text = "Brand: " & Session("BrandSelected")
            CarsList.Items.Add("*** Make a choice ***")

            'Set up to use a stored procedure:
            myCommand.CommandType = CommandType.StoredProcedure
            myCommand.Connection = myDatabaseConnection
            myCommand.CommandText = "SelectProdName"
            myCommand.Parameters.AddWithValue("@TargetBrand", Session("BrandSelected"))

            'Use an SqlDataReader to execute the stored procedure and
            'get the results into the drop down list:
            myDatabaseConnection.Open()
            myReader = myCommand.ExecuteReader()
            While (myReader.Read())
                CarsList.Items.Add(myReader.GetString(0))
            End While

            myDatabaseConnection.Close()
            myDatabaseConnection.Dispose()
        Catch exception As System.Data.SqlClient.SqlException
            ErrorLabel.Visible = True
        Catch exception As Exception
            ErrorLabel.Visible = True
        Finally    'Do cleanup tasks here:
            myCommand = Nothing

            If Not myReader Is Nothing AndAlso _
                Not myReader.IsClosed Then
                myReader.Close()
            End If

            myReader = Nothing

            If Not myDatabaseConnection Is Nothing AndAlso _
                myDatabaseConnection.State = ConnectionState.Open Then
                myDatabaseConnection.Close()
                myDatabaseConnection.Dispose()
            End If

            myDatabaseConnection = Nothing
        End Try
    Else   ' We have a postback.
        TargetModel = CarsList.SelectedItem.Text
        Session.Add("ModelSelected", TargetModel)
        Response.Redirect("Results.aspx")
    End If
End Sub

Stored Procedure for Results Page

  • This page needs a stored procedure to return the product description and product price for the brand and model of car chosen by the user (and saved in session state).
  • Add a new stored procedure that looks like this:

CREATE PROCEDURE db_datareader.SelectModelBrand 
(
    @TargetModel varchar(24),
    @TargetBrand varchar(24)
)
AS
    SET NOCOUNT ON
    SELECT Product.ProdDescription, Product.ProdPrice
FROM Product INNER JOIN CategoryProduct 
ON Product.ProdNum = CategoryProduct.ProdNum
INNER JOIN Category ON CategoryProduct.CategoryNum = Category.CategoryNum
WHERE (Product.ProdName = @TargetModel) AND (Category.CategoryName = @TargetBrand)
    RETURN

  • As usual, save and execute your stored procedure. Give sensible values for the parameters, such as Vanguard for @TargetBrand and Famtastic for @TargetModel. Check that the product description and price for this car are returned.

Results Code-Behind File

  • The code for Page_Load should look like the following.
  • Note that it needs to fill in values (taken from the session state) for both of the parameters to the stored procedure.
  • The brand, model, and price are displayed in labels, while the description is placed into a text box.
  • Eventually we will want to write code to allow the user to add the displayed car to the shopping cart, but we will do that later.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim Price As Decimal
    Dim Model As String
    Dim Brand As String
    Dim myDatabaseConnection As SqlClient.SqlConnection = Nothing
    Dim myCommand As SqlClient.SqlCommand = Nothing
    Dim myReader As SqlClient.SqlDataReader = Nothing

    BrandLabel.Visible = False
    ErrorLabel.Visible = False
    ModelLabel.Visible = False
    PriceLabel.Visible = False
    ProductDescriptionBox.Visible = False

     If Session.Count = 0 Then   ' No session items were supplied.
        ErrorLabel.Visible = True
    Else
        Try
            Model = Session("ModelSelected")
            Brand = Session("BrandSelected")
            Dim connectionString As String = _
                ConfigurationManager.ConnectionStrings("PartsConnectionString").ConnectionString
            myDatabaseConnection = New SqlClient.SqlConnection(connectionString)
            myCommand = New SqlClient.SqlCommand()

            'Set up to use a stored procedure:
            myCommand.CommandType = CommandType.StoredProcedure
            myCommand.Connection = myDatabaseConnection
            myCommand.CommandText = "SelectModelBrand"
            myCommand.Parameters.AddWithValue("@TargetModel", Model)
            myCommand.Parameters.AddWithValue("@TargetBrand", Brand)

            'Use an SqlDataReader to execute the stored procedure and get the results:
            myDatabaseConnection.Open()
            myReader = myCommand.ExecuteReader()
            If myReader.HasRows Then
                myReader.Read()
                ProductDescriptionBox.Text = myReader.GetValue(0)
                ProductDescriptionBox.Visible = True
                Price = myReader.GetValue(1)
                PriceLabel.Text = "Price:  " & String.Format("{0:C}", Price)
                PriceLabel.Visible = True
                BrandLabel.Text = "Selected Brand: " & Brand
                BrandLabel.Visible = True
                ModelLabel.Text = "Selected Model: " & Model
                ModelLabel.Visible = True
            Else
                ErrorLabel.Visible = True
            End If
            myDatabaseConnection.Close()
            myDatabaseConnection.Dispose()
        Catch exception As System.Data.SqlClient.SqlException
            ErrorLabel.Visible = True
        Catch exception As Exception
            ErrorLabel.Visible = True
        Finally    'Do cleanup tasks here:
            myCommand = Nothing

            If Not myReader Is Nothing AndAlso _
                Not myReader.IsClosed Then
                myReader.Close()
            End If

            myReader = Nothing

            If Not myDatabaseConnection Is Nothing AndAlso _
                myDatabaseConnection.State = ConnectionState.Open Then
                myDatabaseConnection.Close()
                myDatabaseConnection.Dispose()
            End If

            myDatabaseConnection = Nothing
        End Try
    End If

VB Code for Search Page

  • Make the Page_Load procedure look like the following.
  • It is essentially the same code that we used in an earlier example.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim Target As String
    If IsPostBack Then   'Search button was clicked
        Page.Validate()   'Have the validators check the user input in the textbox.
        If Page.IsValid Then
            Target = SubstringBox.Text.ToString()
            Session.Add("TargetSubstring", Target)
            Response.Redirect("SearchResults.aspx")
        End If
    End If
End Sub

Stored Procedure for SearchResults Page

  • The SearchResults page has already been set up with a grid view with paging enabled and View buttons to see more details on any of the cars listed.
  • But the code-behind files needs to use a stored procedure to obtain the data to place into this grid view.
  • The stored procedure should return the product (model) name and category (brand) name for any cars whose brand name, model name, or description contain the parameter value as a substring.
  • Add a new stored procedure that looks like this:

CREATE PROCEDURE db_datareader.SelectLikeBrandModelDesc 
(
    @Target varchar(24)
)
AS
    SET NOCOUNT ON
    SELECT Product.ProdName, Category.CategoryName
FROM Product INNER JOIN CategoryProduct 
ON Product.ProdNum = CategoryProduct.ProdNum
INNER JOIN Category ON CategoryProduct.CategoryNum = Category.CategoryNum
WHERE (Product.ProdName LIKE '%' + @Target + '%') 
OR (Category.CategoryName LIKE '%' + @Target + '%')
OR (Product.ProdDescription LIKE '%' + @Target + '%')
ORDER BY Category.CategoryName, Product.ProdName
    RETURN

  • As usual, save and execute your stored procedure. A sensible value to give for the @Target parameter might be sports, since there are several sports cars in our database, Check that the information returned is what is expected.

Search Results Code-Behind File

  • Fill in the following for the Page_Load procedure.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim Substring As String
    Dim myDatabaseConnection As SqlClient.SqlConnection = Nothing
    Dim myCommand As SqlClient.SqlCommand = Nothing
    Dim resultsDataSet As DataSet = Nothing

    If Session.Count = 0 Then   ' No session items were supplied.
        SessionErrorLabel.Visible = True
    Else
        Try
            Substring = Session("TargetSubstring")
            If Substring = "" Then
                SessionErrorLabel.Visible = True
            Else
                Dim connectionString As String = _
                ConfigurationManager.ConnectionStrings("PartsConnectionString").ConnectionString
                myDatabaseConnection = New SqlClient.SqlConnection(connectionString)
                myCommand = New SqlClient.SqlCommand()

                'Set up to use a stored procedure:
                myCommand.CommandType = CommandType.StoredProcedure
                myCommand.Connection = myDatabaseConnection
                myCommand.CommandText = "SelectLikeBrandModelDesc"
                myCommand.Parameters.AddWithValue("@Target", Substring)

                'Use a DataAdapter to execute the stored procedure and
                'get the results into a dataset for display in the gridview:
                Dim adapter As New SqlClient.SqlDataAdapter(myCommand)
                resultsDataSet = New DataSet
                myDatabaseConnection.Open()
                adapter.Fill(resultsDataSet)

                If resultsDataSet.Tables.Item(0).Rows.Count > 0 Then
                    ResultsGridView.DataSource = resultsDataSet
                    ResultsGridView.DataBind()
                    ResultsGridView.Visible = True
                Else
                    NoDataLabel.Visible = True
                End If
                myDatabaseConnection.Close()
                myDatabaseConnection.Dispose()
            End If
        Catch exception As System.Data.SqlClient.SqlException
            DatabaseErrorLabel.Visible = True
        Catch exception As Exception
            ErrorLabel.Visible = True
        Finally    'Do cleanup tasks here:
            myCommand = Nothing
            resultsDataSet = Nothing

            If Not myDatabaseConnection Is Nothing AndAlso _
                myDatabaseConnection.State = ConnectionState.Open Then
                myDatabaseConnection.Close()
                myDatabaseConnection.Dispose()
            End If

            myDatabaseConnection = Nothing
        End Try
    End If
End Sub

  • Also add the following to handle paging in the grid view.
  • Note the line that uses e.NewPageIndex.

Protected Sub ResultsGridView_PageIndexChanging(ByVal sender As Object, _
    ByVal e As GridViewPageEventArgs) Handles ResultsGridView.PageIndexChanging

    Dim Substring As String
    Dim myDatabaseConnection As SqlClient.SqlConnection = Nothing
    Dim myCommand As SqlClient.SqlCommand = Nothing
    Dim resultsDataSet As DataSet = Nothing

    If Session.Count = 0 Then   ' No session items were supplied.
        SessionErrorLabel.Visible = True
    Else
        Try
            Substring = Session("TargetSubstring")
            If Substring = "" Then
                SessionErrorLabel.Visible = True
            Else
                Dim connectionString As String = _
                ConfigurationManager.ConnectionStrings("PartsConnectionString").ConnectionString
                myDatabaseConnection = New SqlClient.SqlConnection(connectionString)
                myCommand = New SqlClient.SqlCommand()

                'Set up to use a stored procedure:
                myCommand.CommandType = CommandType.StoredProcedure
                myCommand.Connection = myDatabaseConnection
                myCommand.CommandText = "SelectLikeBrandModelDesc"
                myCommand.Parameters.AddWithValue("@Target", Substring)

                'Use a DataAdapter to execute the stored procedure and
                'get the results into a dataset for display in the gridview:
                Dim adapter As New SqlClient.SqlDataAdapter(myCommand)
                resultsDataSet = New DataSet
                myDatabaseConnection.Open()
                adapter.Fill(resultsDataSet)

                If resultsDataSet.Tables.Item(0).Rows.Count > 0 Then
                    ResultsGridView.DataSource = resultsDataSet
                    ResultsGridView.PageIndex = e.NewPageIndex 'Change the page index!
                    ResultsGridView.DataBind()
                    ResultsGridView.Visible = True
                Else
                    NoDataLabel.Visible = True
                End If
                myDatabaseConnection.Close()
                myDatabaseConnection.Dispose()
            End If
        Catch exception As System.Data.SqlClient.SqlException
            DatabaseErrorLabel.Visible = True
        Catch exception As Exception
            ErrorLabel.Visible = True
        Finally    'Do cleanup tasks here:
            myCommand = Nothing
            resultsDataSet = Nothing

            If Not myDatabaseConnection Is Nothing AndAlso _
                myDatabaseConnection.State = ConnectionState.Open Then
                myDatabaseConnection.Close()
                myDatabaseConnection.Dispose()
            End If

            myDatabaseConnection = Nothing
        End Try
    End If
End Sub

  • We also need a routine to handle things when the user clicks on a View button to see the details of a particular car.
  • Both the model and brand selected must be put into the session state before redirecting to the Results page.
  • Add the following to your code-behind file.

Protected Sub ResultsGridView_ItemCommand(ByVal Source As Object, _
    ByVal e As GridViewCommandEventArgs) Handles ResultsGridView.RowCommand

    If e.CommandName = "View" Then
        ' Find the index of the row where the user clicked the View button:
        Dim index As Integer = Convert.ToInt32(e.CommandArgument)
        ' Find the model and brand of the item in this row:
        Session.Add("ModelSelected", ResultsGridView.Rows(index).Cells(1).Text)
        Session.Add("BrandSelected", ResultsGridView.Rows(index).Cells(2).Text)
        Response.Redirect("Results.aspx")
    End If
End Sub

  • Recall that Cells(1) refers to column 1 of the row in the grid view that was clicked. This is where we have the model name.
  • Note that numbering starts at 0, so that column 0 is the one containing the View buttons.
  • Column 2 is the last column in the data grid and is where we have the brand name.
  • The Results.aspx page is the same one that the Cars.aspx page sends the user to when a particular car is selected. Here we redirect to the same results page for displaying the detailed information on the selected car, identified by model (ProdName) and brand (CategoryName).

Testing Your App

  • Save all of your files and build your project.
  • View your new web app locally by using Start Without Debugging and check that all pages display correctly and that the database-related code works on all of the pages that use this.
  • Be sure to check that you can look up a product (car) by starting at the brands page where you select a brand of car, then getting redirected to the cars page where you select a model of car, and finally getting redirected to the results page where you see the details on this car.
  • On the search results page be sure to try out the paging links to see that the paging works correctly. Also check the View buttons to see that they send you to the results page for detailed information on the selected product.
  • Publish your app to the live web server and have your web server administrator set it to be an IIS web app. Then check it in a browser by going to the appropriate URL (such as http://cis2.stvincent.edu/username/foldername/Home.aspx). Test it to make sure that everything works here.
  • If this were a real ecommerce app, we would also have the web server administrator require SSL for access to this application.
  • We now have the beginnings of a reasonable ecommerce app, though we have not yet implemented the shopping cart.

Back to the main page for ASP .NET Web Apps



Author: Br. David Carlson
Last updated: November 23, 2008
Disclaimer