of 119
8/14/2019 Diploma Programming 2009
1/119
page 1DIPLOMA PROGRAMMING 2009
TABLE OF CONTENTS
Response Request & Query Strings ............................................ page 2
Variables, Sessions & Query Strings ........................................... page 3
Select Operaton: ADO.NET Object Cheat Sheet ......................... page 4
Generic Flow Chart of the Online Process ................................. page 5
Build Overview ............................................................................... page 5
GridView HyperlinkField .................................................................page 16
HyperlinkField ................................................................................ page 17
Add Product Images ..................................................................... page 29
Add a Shopping Cart Webform ................................................... page 41
Page Dependencies ....................................................................... page 47
Modify the GridView .................................................................... page 49
Code the Increase, Decrease and Remove Buttons ................... page 56
Finding Items in the GridView ....................................................... page 59
Postbacks ...................................................................................... page 68
Key Terms .................................................................................... page 69Tokens .......................................................................................... page 73
Checkout Process .......................................................................... page 76
ASP.NET Validation Controls ........................................................ page 79
Customerdetails.aspx - Cancel & Submit .....................................page 83
Checkout.aspx ............................................................................... page 87
Content Management System (CMS) ............................................ page 94
The SELECT Statement ................................................................. page 102
The INSERT INTO Statement ......................................................... page 104
The UPDATE Statement ................................................................. page 106
The DELETE Statement ................................................................. page 107
Stack Overflow ................................................................................ page 109CMS Part 2 .......................................................................................page 109
Bridging the Gap between Programmers and the Vision ........... page 112
Creating a Masterpage ................................................................... page 113
Creating the Connection String .....................................................page 117
CMS Part 3 .......................................................................................page 118
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
2/119
page 2DIPLOMA PROGRAMMING 2009
Friday, January 16, 2009
Welcome
Wednesday, February 11, 2009
Response Request & Query Strings Requests between servers and browsers are handled via HTTP - Hypertext Transfer Protocol. HTTPis a stateless protocol. This means that each request is serviced as it comes; after the request is
processed, all of the data is discarded. No state is maintained across requests even from the sameclient.
Response Object - a property of the HttpResponse object.This represents the outgoing data from the current Web form object. We can use the Redirectmethod to navigate to a new Web form.
response.redirect("nextpage.aspx")
As you can see, the redirect method requires a URL string.
Request Object - a property of the HttpRequest object.This represents incomming data to the current Web form. We can read the properties of theHttpRequest object to learn more about the client and the page currently being viewed.
lblURL.Text = Request.Url.ToString
Query StringsA Query String is composed of field-value pairs and is appended to a URL.
response.redirect("pagename.aspx?FieldName=Value")
Query Strings are useful for passing non sensitive data between 2 pages.
We can use the request object to read the values of the fields within the Query String.
Dim X as String = Request.QueryString("FieldName")
Copyright Rachael Colley, 2009
http://diplomaprogramming.blogspot.com/2009/01/welcome.htmlhttp://diplomaprogramming.blogspot.com/2009/02/response-request-query-strings.htmlhttp://diplomaprogramming.blogspot.com/2009/02/response-request-query-strings.htmlhttp://diplomaprogramming.blogspot.com/2009/01/welcome.html8/14/2019 Diploma Programming 2009
3/119
page 3DIPLOMA PROGRAMMING 2009
Wednesday, February 11, 2009
Variables, Sessions & Query Strings So how do you know when to use a Variable, a Session or a Query String? The short answer is itdepends on what you are trying to do.
As we have already discussed, HTTP is a stateless environment, so if you want to keep track of avalue for the life of a users visit then a Session Variable would be a good choice.
If you just need to send a non-sensitive value from one page to the next page, a Query String would be a good choice.
Variables can be used where processing needs to occur within a single event. This processing mayalso include the value of Sessions and Query Strings.
Sensitive DataThere is an important exception to what is written above. Remember when we did the Query Stringtutorial and you were asked to note the value of the Query String in the address bar? Well, put it thisway - if You can see the Query String value, so can a malicious user.In the case of sensitive data, itis best to use a Session Variable. Why? Because Sessions Variables are held on the server and arenever sent to the client, therefore they are much more secure.
What is sensitive data? The following items may be considered sensitive data - ID's such asCustomerID, Account Numbers, Addresses etc.Posted by RSColley at 1:45 PM 0 comments Links to this post Labels: Query Strings , sensitive data , sessions , variables
Session Variables Requests between servers and browsers are handled via HTTP - Hypertext Transfer Protocol. HTTPis a stateless protocol. This means that each request is serviced as it comes; after the request is
processed, all of the data is discarded. No state is maintained across requests even from the sameclient.
In a nutshell, data from one page is generally unavailable on the next page etc.When we create a Desktop Application, often we use variables to hold data that persists for the lifeof the program execution. There are several ways to achieve the same result on the ASP.NET
platform. One way is to use Session Variables.
A Session Variable can be read from anywhere in your website. You can use them to storeinformation for the lifetime of a single users visit. Session variables do not need to be declared, theycan be written on the fly.
Session("SessionName") = value
That's not to say that we have stopped using variables. not at all. But in this environment we can no
longer rely on them to store application wide data.
Copyright Rachael Colley, 2009
http://diplomaprogramming.blogspot.com/2009/02/variables-sessions-query-strings.htmlhttp://diplomaprogramming.blogspot.com/2009/02/variables-sessions-query-strings.htmlhttp://diplomaprogramming.blogspot.com/2009/02/variables-sessions-query-strings.html#commentshttp://diplomaprogramming.blogspot.com/2009/02/variables-sessions-query-strings.html#linkshttp://diplomaprogramming.blogspot.com/search/label/Query%20Stringshttp://diplomaprogramming.blogspot.com/search/label/sensitive%20datahttp://diplomaprogramming.blogspot.com/search/label/sessionshttp://diplomaprogramming.blogspot.com/search/label/sessionshttp://diplomaprogramming.blogspot.com/search/label/variableshttp://diplomaprogramming.blogspot.com/2009/02/session-variables.htmlhttp://www.blogger.com/post-edit.g?blogID=563724260557473738&postID=2203798235344311607http://www.blogger.com/email-post.g?blogID=563724260557473738&postID=2203798235344311607http://diplomaprogramming.blogspot.com/2009/02/variables-sessions-query-strings.htmlhttp://diplomaprogramming.blogspot.com/2009/02/variables-sessions-query-strings.htmlhttp://diplomaprogramming.blogspot.com/2009/02/variables-sessions-query-strings.html#commentshttp://diplomaprogramming.blogspot.com/2009/02/variables-sessions-query-strings.html#linkshttp://diplomaprogramming.blogspot.com/search/label/Query%20Stringshttp://diplomaprogramming.blogspot.com/search/label/sensitive%20datahttp://diplomaprogramming.blogspot.com/search/label/sessionshttp://diplomaprogramming.blogspot.com/search/label/variableshttp://diplomaprogramming.blogspot.com/2009/02/session-variables.html8/14/2019 Diploma Programming 2009
4/119
page 4DIPLOMA PROGRAMMING 2009
Wednesday, February 18, 2009
Select Operation: ADO.NET Object Cheat Sheet Connection String (The road)
A Connection String is a string in which we specify the database we want to connect to, and provideany authentication details.
Data Source=.\SQLEXPRESS;AttachDbFilename=E:\Blogger.mdf;integrated security=true
The connection string must specify the name of the computer on which the database is located. Alsorequired are the name of the database. In the Live environment, a user ID and the password are alsorequired.
Connection Object (The car)Facilitates a connection to the database using the aforementioned connection string.
Command Object (The shopping list)Represents an SQL statement to execute against a data source.
DataAdapter Object (Mum doing the shopping)Uses the Command object and the Connection object to return results from the data source to theapplication.
Dataset Object (The pantry)Represents an in-memory cache of the data retrieved from the data source.
Wednesday, February 25, 2009
Interested in following the Cert IV blog? If you would also like to follow the CertIV blog, here is the URL:
http://c4programming.blogspot.com/
Posted by RSColley at 1:19 PM 0 comments Links to this post
Copyright Rachael Colley, 2009
http://diplomaprogramming.blogspot.com/2009/02/select-operation-adonet-object-cheat.htmlhttp://diplomaprogramming.blogspot.com/2009/02/interested-in-following-cert-iv-blog.htmlhttp://c4programming.blogspot.com/http://diplomaprogramming.blogspot.com/2009/02/interested-in-following-cert-iv-blog.htmlhttp://diplomaprogramming.blogspot.com/2009/02/interested-in-following-cert-iv-blog.html#commentshttp://diplomaprogramming.blogspot.com/2009/02/interested-in-following-cert-iv-blog.html#linkshttp://www.blogger.com/post-edit.g?blogID=563724260557473738&postID=1141370278881655683http://www.blogger.com/email-post.g?blogID=563724260557473738&postID=1141370278881655683http://diplomaprogramming.blogspot.com/2009/02/select-operation-adonet-object-cheat.htmlhttp://diplomaprogramming.blogspot.com/2009/02/interested-in-following-cert-iv-blog.htmlhttp://c4programming.blogspot.com/http://diplomaprogramming.blogspot.com/2009/02/interested-in-following-cert-iv-blog.htmlhttp://diplomaprogramming.blogspot.com/2009/02/interested-in-following-cert-iv-blog.html#commentshttp://diplomaprogramming.blogspot.com/2009/02/interested-in-following-cert-iv-blog.html#links8/14/2019 Diploma Programming 2009
5/119
page 5DIPLOMA PROGRAMMING 2009
Generic flow chart of the online shopping process
This is a generic flow chart of the online shopping process we are going to build during weeks 3 to8.
Thursday, February 26, 2009Week 3 tut notes
You can view extensive tutorial notes for week 3 here:
Topic: What we are going to build in the next 5 weeks (6 including this week)
Copyright Rachael Colley, 2009
http://diplomaprogramming.blogspot.com/2009/02/generic-flow-chart-of-online-shopping.htmlhttp://docs.google.com/Doc?id=dfvxqtdd_156gbzg4xg3http://2.bp.blogspot.com/_9NT2_IudVWY/SaR6plytTZI/AAAAAAAAAD4/wpurfVra9pU/s1600-h/OnlineShoppingFlowChart.gifhttp://diplomaprogramming.blogspot.com/2009/02/generic-flow-chart-of-online-shopping.htmlhttp://docs.google.com/Doc?id=dfvxqtdd_156gbzg4xg38/14/2019 Diploma Programming 2009
6/119
page 6DIPLOMA PROGRAMMING 2009
Topic: Start the build
Create new database
Create a new website called Online Shopping
Add a new database called XYZStore.mdf
Add a new table Create a new table called XYZCategories with the following columns:
Don't forget to add the Primary Key and set the CategoryID column as the Identity column
Populate table
Populate XYZCategories with the following records:
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
7/119
page 7DIPLOMA PROGRAMMING 2009
Create Interface
Using your favourite HTML editor create a simple interface with the following structure &approximate dimensions :
Save your interface
Create a Master Page Add a Master Page to the project called OnlineShopping.Master
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
8/119
page 8DIPLOMA PROGRAMMING 2009
Locate the code for the two content place holders and delete them (They are shaded red inthe screen-shot below).
Return to the HTML view of your interface
Copy all of the code between the body tags
Return to the Master Page and select everything between the form tags
Paste your HTML between the form tags (Shaded red in the screen-shot below).
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
9/119
page 9DIPLOMA PROGRAMMING 2009
If you have used an external style sheet, add it to the project now via the Add Existing Itemmenu.
Make sure to add the link to the style sheet in the head tag of the master page
Return to Design View to view your interface and ensure it is displaying correctly
Add a Content Placeholder
A Content Place Holder will now define the are of the interface that is editable on every pagecreated from the Master Page.
From the Toolbox, drag a Content Place Holder to the content pane of your interface.
Master Page layout now complete
Now you can choose to add items to the Master page that should be displayed on each page of the site.
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
10/119
page 10DIPLOMA PROGRAMMING 2009
Add a GridView control
From the Data section of the Toolbox, drag a GridView control into the left pane of your interface
Name the GridView gvProducts
note the source view
In Design View, click the small arrow on the edge of the control to open the GridView tasksmenu
select Edit Columns from this list
GridView Control Fields
The following is a list of the type of fields you can add to a GridView:
BoundField : The BoundField is used to display the value of a field as text.
CheckBoxField : The CheckBoxField is used to display the value of a Boolean(True/False) data field in a CheckBox.
HyperLinkField : The HyperLinkField is used to display a hyperlink for eachrecord displayed. When the user clicks a hyperlink, he or she is directed to theweb page associated with the hyperlink.
ImageField : The ImageField is used to display an image for each record
displayed.
ButtonField : The ButtonField is used to display a button for each record that is
displayed.
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
11/119
page 11DIPLOMA PROGRAMMING 2009
CommandField : The CommandField is a special field used to display command buttons that perform delete, edit, insert, or select operations.
TemplateField : The TemplateField is used to display custom content for each
record displayed.
we will not add any fields at this point
note the Auto-Generate fields checkbox is checked
click OK
Create Connection String
Connection strings can be stored on individual pages of your application but it is best for security and ease of development to store that connection string in one central and secure place.
The following code creates a connection string to the database
Copy the code below:
8/14/2019 Diploma Programming 2009
12/119
page 12DIPLOMA PROGRAMMING 2009
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NameOfYourDatabase.mdf;integratedsecurity=true; User Instance=True" providerName="System.Data.SqlClient"/>
Open web.config
Locate the following lines:
Highlight them and then paste in the connection string from above
Ensure that the name of the database is correct
Populate the GridView
The code below gets all of the records from the XYZCategories table. Enter the following code in the load event of the master page:
Dim ConnectionStringLocation As ConnectionStringSettings =System.Configuration.ConfigurationManager.ConnectionStrings("Connstring")Dim ConnString As String = ConnectionStringLocation.ToStringDim MyDataSource As New SqlDataSource(ConnString, "")
Dim MyConnection As New Data.SqlClient.SqlConnection(MyDataSource.ConnectionString)Dim cmdGetCategories As New Data.SqlClient.SqlCommandWith cmdGetCategories
.Connection = MyConnection
.CommandType = Data.CommandType.Text
.CommandText = "SELECT * FROM XYZCategories"
End WithDim dsResults As New Data.DataSetDim daDataAdapter As New Data.SqlClient.SqlDataAdapter(cmdGetCategories)daDataAdapter.Fill(dsResults, "GetCategoriesQuery")
MyConnection.Open()MyConnection.Close()
cmdGetCategories = NothingdaDataAdapter = Nothing
The code below DataBinds the results of the database operation to the GridView.
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
13/119
page 13DIPLOMA PROGRAMMING 2009
Enter the following code beneath the code above:
gvCategories.DataSource = dsResultsgvCategories.DataMember = "GetCategoriesQuery"gvCategories.DataKeyNames = New String() {"CategoryID"}gvCategories.DataBind()
Create a home page Delete default.aspx from Solution Explorer
Add a new Webform to the project and call it default.aspx
Before you click Add, be sure to check the Select Master Page checkbox at the bottom
On the next screen, select the name of your Master Page from the list and click OK
Notice that the source view for default.aspx only contains VB page directives and theopening and closing tags for the content place holder
Switch to Design view and note that the only region of the page that you can edit is the areawithin the content place holder
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
14/119
page 14DIPLOMA PROGRAMMING 2009
Run the project (Click OK to modify the web.config file to allow debugging)
Note that the GridView has populated with all columns and records from the XYZCategoriestable
Create the Products table Create a new table called XYZProducts with the following columns:
Don't forget to add the Primary Key and set the ProductID column as the Identity column.
Populate the Products table Populate the Products table with 3 products for each category.
Modify the GridView
Now we will modify the Gridview to display our category names as hyperlinks. Each hyperlink willhave a query string sending the CategoryID to the next page.
Return to the fields dialog of the GridView
Uncheck the Auto-generate fields checkbox
Select a HyperlinkField and click Add
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
15/119
page 15DIPLOMA PROGRAMMING 2009
Set the following properties for the HyperlinkField
DataNavigateURLField : CategoryID DataNavigateURLFormatString : ~/products.aspx?CategoryID={0} DataTextFormatString : CategoryID
Click OK
Add a new Webform to display products Add a new Webform to the project and call it products.aspx
Don't forget to the check the Select Master Page checkbox
Locate the title property of the page and call it Products
Add the GridView control In the content area of the page, add a Gridview & call it gvProducts
Open the Fields dialog of the GridView and add the following columns:
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
16/119
page 16DIPLOMA PROGRAMMING 2009
HyperlinkField HeaderText : Product Name
DataNavigateURLField : ProductID DataNavigateURLFormatString : ~/productdetails.aspx?ProductID={0} DataTextFormatString : ProductID
BoundField HeaderText : Price DataField : Price
Run & test the project.
Don't worry if you get a Resource not found error - this is just letting you know that the page productdetails.aspx cannot be found and this is because we have not created it yet.
Edit this page (if you have permission) | Google Docs -- Web word processing, presentations and spreadsheets.
Planning your online store interface Don't forget - plan for your categories to drop down the left hand side of your interface.
Friday, February 27, 2009
GridView HyperlinkField When we want a result in our GridView to render out as a Hyperlink, we use a HyperlinkField.There are three properties that we need to set if we want that hyperlink to go to a particular pageand include a Query String name value pair.
For eg.
We want our HyperlinkField to be a category name from the datasource.
Copyright Rachael Colley, 2009
http://docs.google.com/Edit?tab=edit&dr=true&docid=dfvxqtdd_156gbzg4xg3http://docs.google.com/http://diplomaprogramming.blogspot.com/2009/02/planning-your-online-store-interface.htmlhttp://diplomaprogramming.blogspot.com/2009/02/gridview-hyperlinkfield.htmlhttp://docs.google.com/Edit?tab=edit&dr=true&docid=dfvxqtdd_156gbzg4xg3http://docs.google.com/http://diplomaprogramming.blogspot.com/2009/02/planning-your-online-store-interface.htmlhttp://diplomaprogramming.blogspot.com/2009/02/gridview-hyperlinkfield.html8/14/2019 Diploma Programming 2009
17/119
page 17DIPLOMA PROGRAMMING 2009
Set the DataTextField property: CategoryName
Now when the user clicks the hyperlink, we want the them to be sent to a page called products butwe also want to include the CategoryID of the selected item in a query string.Set the DataNavigateURLFormatString property: ~/products.aspx?CategoryID={0}
What is the {0}? Well, you must set the DataNavigateURLFields property to the name from thedatasource that contains the CategoryID, in this case CategoryID.
Now wehn the user clicks this link, they will be sent to products.aspx with the category ID includedin the query string.
Clear as mud?
Posted by RSColley at 3:09 PM 0 comments Links to this post Labels: DataNavigateURLFields , DataNavigateURLFormatString , DataTextField , GridView
Creating product images An important thing to note when creating product images for your store: make sure each image is asquare. This will ensure that they render out in a predictable fashion.
Wednesday, March 4, 2009Week 4 tut notes PART 1
Summary
At this stage we have a MasterPage which displays our categories in a GridViewobject(gvCategories) and a Products page that displays the products from the selected category -also in a GridView object(gvProducts).
Both our category names and product names are displayed to the user as hyperlinks so that whenthey make a selection, we can send them further along the shop chain.
As you will recall, we used a HyperlinkField for this purpose. We set a number of the Hyperlink controls properties so that certain things would occur when the user made a selection.
For instance, these are the properties we set for the Hyperlink control on the Products page(gvProducts):
HyperlinkField
HeaderText : Product Name
Copyright Rachael Colley, 2009
http://diplomaprogramming.blogspot.com/2009/02/gridview-hyperlinkfield.htmlhttp://diplomaprogramming.blogspot.com/2009/02/gridview-hyperlinkfield.html#commentshttp://diplomaprogramming.blogspot.com/2009/02/gridview-hyperlinkfield.html#linkshttp://diplomaprogramming.blogspot.com/search/label/DataNavigateURLFieldshttp://diplomaprogramming.blogspot.com/search/label/DataNavigateURLFieldshttp://diplomaprogramming.blogspot.com/search/label/DataNavigateURLFormatStringhttp://diplomaprogramming.blogspot.com/search/label/DataNavigateURLFormatStringhttp://diplomaprogramming.blogspot.com/search/label/DataTextFieldhttp://diplomaprogramming.blogspot.com/search/label/GridViewhttp://diplomaprogramming.blogspot.com/2009/02/creating-product-images.htmlhttp://www.blogger.com/post-edit.g?blogID=563724260557473738&postID=3282675379657923156http://www.blogger.com/email-post.g?blogID=563724260557473738&postID=3282675379657923156http://diplomaprogramming.blogspot.com/2009/02/gridview-hyperlinkfield.htmlhttp://diplomaprogramming.blogspot.com/2009/02/gridview-hyperlinkfield.html#commentshttp://diplomaprogramming.blogspot.com/2009/02/gridview-hyperlinkfield.html#linkshttp://diplomaprogramming.blogspot.com/search/label/DataNavigateURLFieldshttp://diplomaprogramming.blogspot.com/search/label/DataNavigateURLFormatStringhttp://diplomaprogramming.blogspot.com/search/label/DataTextFieldhttp://diplomaprogramming.blogspot.com/search/label/GridViewhttp://diplomaprogramming.blogspot.com/2009/02/creating-product-images.html8/14/2019 Diploma Programming 2009
18/119
page 18DIPLOMA PROGRAMMING 2009
DataNavigateURLField : ProductID DataNavigateURLFormatString : ~/productdetails.aspx?ProductID={0} DataTextFormatString : ProductID
By setting the properties in this way, we made sure that the Product name was displayed as a link and when the user made a selection they would be sent to Products.aspx with the ProductIDincluded in the URL as a query string.
It was important to send the ID through to the next page so that we could use it to get all of theinformation about the product from the database.
And now we continue...
Add Product Images
Now we are going to display an image for each product in the gridview on Products.aspx.
For the purposes of this assignment, product images should be jpg files and each should benamed after the corresponding product ProductID.
An important thing to note when creating product images for your store: make sure eachimage is a square. This will ensure that they render out in a predictable fashion.
For eg. A product with the ProductID 5 should have an image named 5.jpg Locate the product images folder on X drive and add this to your project via the Add
Existing Item option
The screenshot above shows solution explorer at this point. Open the Fields dialog of the GridView and select an ImageField and then click Add
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
19/119
page 19DIPLOMA PROGRAMMING 2009
From the properties list on the right, enter values for the following properties:
Header Text : Image DataImageURLField : ProductID DataImageURLFormatString : ~/ProductImages/{0}.jpg ControlStyle/Width : 50 ControlStyle/Height : 50
As you can see, the DataImageURLFormatString points to the product images folder and includes a placeholder for the name of the image. The DataImageURLField has been set to ProductID and it isthis that will be substituted for the {0} in the DataImageURLFormatString at run time so that it willactually look something like this:
ProductImages/10.jpg Run and test the project
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
20/119
page 20DIPLOMA PROGRAMMING 2009
Note that each product now has image
Display the Category name on Products.aspx
Next we will modify the properties in the GridView on our master page (gvCategories) so that theCategoryName is also sent to the next page in the query string.
Return to OnlineStore.Master and open the fields dialog
Select Categories from the Selected Fields list
Modify the following properties to say the following:
DataNavigateURLFields : CategoryID ,CategoryName DataNavigateURLFormatString : ~/products.aspx?
CategoryID={0} &CategoryName={1}
We have now created a placeholder for CategoryName in the same way that wecreated a placeholder in the query string for CategoryID. {0} will be substituted for the
items CategoryID and {1} will be substituted for the items CategoryName.
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
21/119
page 21DIPLOMA PROGRAMMING 2009
({0} being the first item found in the r ecord and {1} being the second)
Run the project, click on a category and view the results in the address bar of your browser.
In my example I have clicked Nails from the categories list. Above you can see 2 Name-Value pairsin the Query string now. One for CategoryID (=4) and another for CategoryName (=Nails).
Place a Label called lblCategoryName on Products.aspx somewhere above gvProducts
Create CategoryID & CategoryName sessions
Now that we have both the CategoryID and CategoryName being sent through to products.aspx,let's create a session for each because we may need to read those values on subsequent pages(remember, a query string is good for sending data from one page to the next but is not great for carrying data around an entire site).
Enter the following code in the Load event:
Session("CategoryName") = Request.QueryString("CategoryName") Session("CategoryID") = Request.QueryString("CategoryID")
Me.lblCategoryName.Text = Session("CategoryName")
Run and test your project
Note that the text property of lblCategoryName is now populated with the contents of theCategoryName query string
Note the ProductID and CategoryName in the query string
Add a Product Details Webform Add a new webform to the project and call it ProductDetails.aspx
Remember to check the Select Master Page checkbox
This page will be used to view the full product details of the product. We will also use a
LinkButton to display the CategoryName (we will get that name from the CategoryName session).
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
22/119
page 22DIPLOMA PROGRAMMING 2009
Add the following controls:
lnkCategoryName (LinkButton)
imgProduct lblProductName
lblDescription
lblPrice
lblError (Visible: False)
hfProductID (This control is called a HiddenField. Visible: False)
lblQuantityWarning (Text: Please select a quantity first!! Visible: False)
Display the Category Name
Again we will use the value stored in our CategoryName session to display on our interface. Enter the following code in the Load event of productdetails.aspx :
lnkCategoryName.Text = Session("CategoryName")
Database operation to get the Product Details
Now, let's get what we need from the database.
This time we are using the SELECT statement to select all of the fields for a single record - therecord with the ProductID the user selected on the previous page. This ProductID has been sentthrough via query string so we have everything we need to get the correct product to display.
Enter the following code in the Load event of ProductDetails.aspx :
Dim ConnectionStringLocation As ConnectionStringSettings =System.Configuration.ConfigurationManager.ConnectionStrings("Connstring")
Dim ConnString As String = ConnectionStringLocation.ToString
Dim MyDataSource As New SqlDataSource(ConnString, "")
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
23/119
page 23DIPLOMA PROGRAMMING 2009
Dim MyConnection As New Data.SqlClient.SqlConnection(MyDataSource.ConnectionString)
Dim cmdGetProducts As New Data.SqlClient.SqlCommand With cmdGetProducts
.Connection = MyConnection
.CommandType = Data.CommandType.Text
.CommandText = " SELECT * FROM XYZProducts WHERE ProductID=@ProductID "
. Parameters.AddWithValue("@ProductID", Request.QueryString("ProductID"))
End WithDim dsResults As New Data.DataSet Dim daDataAdapter As New Data.SqlClient.SqlDataAdapter(cmdGetProducts)daDataAdapter.Fill(dsResults, "GetProductDetailsQuery")
MyConnection.Open()MyConnection.Close()
cmdGetProducts = Nothing daDataAdapter = Nothing
Populate labels and Hidden Field with the Product Details
We are going to use a HiddenField control to store the ProductID for use if we need to addthe product to the cart.
Once the database operation is complete, hopefully we have found the product record wewish to display and it is sitting in our dataset object(dsResults) under our namedquery(GetProductDetailsQuery).
You will notice the first thing that happens in the code is that we use an If Else statement tocheck if there are any rows in dsResults.GetProductDetails. If the row count does not equal 0,
then the labels populate. If not, an error message is displayed to the user and we avoid acrash.
It is important that we never take for granted the presence of data in the database or we mayfind that our sites crash.
Immediately beneath the last chunk of code, enter the following:
If dsResults.Tables("GetProductDetailsQuery").Rows.Count 0 Then Me.imgProduct.ImageUrl = Server.MapPath("~/productimages/" &dsResults.Tables("GetProductDetailsQuery").Rows(0).Item("ProductID").ToString & ".jpg")
Me.lblProductName.Text =
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
24/119
page 24DIPLOMA PROGRAMMING 2009
dsResults.Tables("GetProductDetailsQuery").Rows(0).Item("ProductName")Me.lblDescription.Text =
dsResults.Tables("GetProductDetailsQuery").Rows(0).Item("Description")Me.lblPrice.Text =
dsResults.Tables("GetProductDetailsQuery").Rows(0).Item("Price")Else
Me.lblError.Visible = True Me.lblError.Text = "This product was not found. Please select another." hfPoductID.Value =dsResults.Tables("GetProductDetailsQuery").Rows(0).Item("ProductID")
End If
Run and test the project
FormatCurrency() method
You will notice that the price of our product is displaying as a simple decimal figure. It would bemuch better if we could display this value as currency.
Locate the line of code that sets the text property of lblPrice and modify it so it reads:
Me.lblPrice.Text = FormatCurrency(dsResults.Tables("GetProductDetailsQuery").Rows(0).Item("Price"))
Run and test the project
Where do we go from here?
OK, our website is now at the point where the user can choose to add the item to the cart. We arealso going to give them the option of returning to the list of products in the category they selected.
Let's work on the latter first.
You will recall we now have two active sessions - CategoryName and CategoryID . The categoryname session has been handy in that it has allowed us to display the category name on each page.The category ID will now also become handy because we are going to use it on productdetails.aspxif the user chooses to browse back to the list of products they came from.
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
25/119
page 25DIPLOMA PROGRAMMING 2009
Category Name LinkButton
When the user clicks this button, we are going to send them back to products.aspx with theCategoryID and CategoryName in a query string.
Why are we placing sessions in a query string? - Because the code on products.aspxthat gets the products from the database AND the code that places the CategoryName inthe label will be expecting to read the CategoryID and CategoryName from the querystring.
Got it? If your not sure, have a look right now. Enter the following code in the Click event of lnkCategoryName :
Response.Redirect("products.aspx?CategoryID=" & Session("CategoryID") &"&CategoryName=" & Session("CategoryName"))
Run and test the project
Page dependencies
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
26/119
page 26DIPLOMA PROGRAMMING 2009
You will find that many pages in your store will have dependencies - that is, they are pages thatcannot load until they are given some form of data such as a query string or access to a sessionvariable. products.aspx is one such page. It is dependant on the contents of the query stringcontaining the CategoryName and CategoryID.
You could try the following to watch products.aspx crash (a good demonstration of pagedependencies):
Comment out the code the code in the lnkCategoryName Click event and replace it with thefollowing:
Response.Redirect("products.aspx")
Run and test the project
Here's a screen shot of the error:
(Make sure you replace your original code after running this test.)
Add to cart
Now we will give our user the ability to add the item to the cart for purchase. But before we allowthem to do so, we are going to require them to select a quantity.
Select Quantity Add a DropDownList to productdetails.aspx and name it ddlQuantity
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
27/119
page 27DIPLOMA PROGRAMMING 2009
In the Items property click Add to add items 1 to 5 in the Text property. Leave the Value property as default. Shown below:
Note the index of each item position in the list beginning with 0.
Add To Cart Button Add a button to productdetails.aspx and call it btnAddToCart
Give the button a text property of "Add to cart"
Input Validation: Make sure the user has made a quantity selection before clicking
We are going to use an If Else statement to ensure that the user has made a selection from thequantity drop down list.
You will notice in the code below, the first line is checking that the SelectedIndex is greater that0. If you take another look at your drop down lost, you will see that the item with an Index of 0 isthe item that says "Select Quantity". Obviously we don't want to allow this selection because it isnot a quantity selection at all.
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
28/119
page 28DIPLOMA PROGRAMMING 2009
If the condition tests true (that an index greater than 0 was selected), we shoot the use off to thecart with the ProductID and the quantity in the query string.
If the condition does not test true , the statement jumps straight to the Else in which a warning isgiven to the user about selecting a quantity first.
Enter the following code in the Click event of btnAddToCart :
If ddlQuantity.SelectedIndex > 0 ThenResponse.Redirect("shoppingcart.aspx?ProductID=" & hfPoductID.Value.ToString &
"&Quantity=" & ddlQuantity.SelectedItem.ToString) Else
lblQuantityWarning.Visible = True End If
Run and test the project
Don't despair when you get the following error, it is just letting you know that it cannot findshoppingcart.aspx - which is fine because we haven't created it yet.
The most important thing to note at this point is the query string in the address bar. Boththe ProductID and the Quantity are present, ready for our INSERT operation.
Shown below:
Conclusion of Part 1
Ok, in part 2 we are going to build the shopping cart.
Edit this page (if you have permission) |
Google Docs -- Web word processing, presentations and spreadsheets.
Copyright Rachael Colley, 2009
http://docs.google.com/Edit?tab=edit&dr=true&docid=dfvxqtdd_159c84xvfr9http://docs.google.com/http://docs.google.com/Edit?tab=edit&dr=true&docid=dfvxqtdd_159c84xvfr9http://docs.google.com/8/14/2019 Diploma Programming 2009
29/119
page 29DIPLOMA PROGRAMMING 2009
Wednesday, March 4, 2009Week 4 tut notes PART 1
Summary
At this stage we have a MasterPage which displays our categories in a GridViewobject(gvCategories) and a Products page that displays the products from the selected category -
also in a GridView object(gvProducts).Both our category names and product names are displayed to the user as hyperlinks so that whenthey make a selection, we can send them further along the shop chain.
As you will recall, we used a HyperlinkField for this purpose. We set a number of the Hyperlink controls properties so that certain things would occur when the user made a selection.
For instance, these are the properties we set for the Hyperlink control on the Products page(gvProducts):
HyperlinkField HeaderText : Product Name DataNavigateURLField : ProductID DataNavigateURLFormatString : ~/productdetails.aspx?ProductID={0} DataTextFormatString : ProductID
By setting the properties in this way, we made sure that the Product name was displayed as a link and when the user made a selection they would be sent to Products.aspx with the ProductIDincluded in the URL as a query string.
It was important to send the ID through to the next page so that we could use it to get all of theinformation about the product from the database.
And now we continue...
Add Product Images
Now we are going to display an image for each product in the gridview on Products.aspx.
For the purposes of this assignment, product images should be jpg files and each should benamed after the corresponding product ProductID.
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
30/119
page 30DIPLOMA PROGRAMMING 2009
An important thing to note when creating product images for your store: make sure eachimage is a square. This will ensure that they render out in a predictable fashion.
For eg. A product with the ProductID 5 should have an image named 5.jpg Locate the product images folder on X drive and add this to your project via the Add
Existing Item option
The screenshot above shows solution explorer at this point. Open the Fields dialog of the GridView and select an ImageField and then click Add
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
31/119
page 31DIPLOMA PROGRAMMING 2009
From the properties list on the right, enter values for the following properties:
Header Text : Image DataImageURLField : ProductID DataImageURLFormatString : ~/ProductImages/{0}.jpg ControlStyle/Width : 50 ControlStyle/Height : 50
As you can see, the DataImageURLFormatString points to the product images folder and includes a placeholder for the name of the image. The DataImageURLField has been set to ProductID and it isthis that will be substituted for the {0} in the DataImageURLFormatString at run time so that it willactually look something like this:
ProductImages/10.jpg Run and test the project
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
32/119
page 32DIPLOMA PROGRAMMING 2009
Note that each product now has image
Display the Category name on Products.aspx
Next we will modify the properties in the GridView on our master page (gvCategories) so that theCategoryName is also sent to the next page in the query string.
Return to OnlineStore.Master and open the fields dialog
Select Categories from the Selected Fields list
Modify the following properties to say the following:
DataNavigateURLFields : CategoryID ,CategoryName DataNavigateURLFormatString : ~/products.aspx?
CategoryID={0} &CategoryName={1}
We have now created a placeholder for CategoryName in the same way that wecreated a placeholder in the query string for CategoryID. {0} will be substituted for the
items CategoryID and {1} will be substituted for the items CategoryName.
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
33/119
page 33DIPLOMA PROGRAMMING 2009
({0} being the first item found in the r ecord and {1} being the second)
Run the project, click on a category and view the results in the address bar of your browser.
In my example I have clicked Nails from the categories list. Above you can see 2 Name-Value pairsin the Query string now. One for CategoryID (=4) and another for CategoryName (=Nails).
Place a Label called lblCategoryName on Products.aspx somewhere above gvProducts
Create CategoryID & CategoryName sessions
Now that we have both the CategoryID and CategoryName being sent through to products.aspx,let's create a session for each because we may need to read those values on subsequent pages(remember, a query string is good for sending data from one page to the next but is not great for carrying data around an entire site).
Enter the following code in the Load event:
Session("CategoryName") = Request.QueryString("CategoryName") Session("CategoryID") = Request.QueryString("CategoryID")
Me.lblCategoryName.Text = Session("CategoryName")
Run and test your project
Note that the text property of lblCategoryName is now populated with the contents of theCategoryName query string
Note the ProductID and CategoryName in the query string
Add a Product Details Webform Add a new webform to the project and call it ProductDetails.aspx
Remember to check the Select Master Page checkbox
This page will be used to view the full product details of the product. We will also use a
LinkButton to display the CategoryName (we will get that name from the CategoryName session).
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
34/119
page 34DIPLOMA PROGRAMMING 2009
Add the following controls:
lnkCategoryName (LinkButton)
imgProduct lblProductName
lblDescription
lblPrice
lblError (Visible: False)
hfProductID (This control is called a HiddenField. Visible: False)
lblQuantityWarning (Text: Please select a quantity first!! Visible: False)
Display the Category Name
Again we will use the value stored in our CategoryName session to display on our interface. Enter the following code in the Load event of productdetails.aspx :
lnkCategoryName.Text = Session("CategoryName")
Database operation to get the Product Details
Now, let's get what we need from the database.
This time we are using the SELECT statement to select all of the fields for a single record - therecord with the ProductID the user selected on the previous page. This ProductID has been sentthrough via query string so we have everything we need to get the correct product to display.
Enter the following code in the Load event of ProductDetails.aspx :
Dim ConnectionStringLocation As ConnectionStringSettings =System.Configuration.ConfigurationManager.ConnectionStrings("Connstring")
Dim ConnString As String = ConnectionStringLocation.ToString
Dim MyDataSource As New SqlDataSource(ConnString, "")
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
35/119
page 35DIPLOMA PROGRAMMING 2009
Dim MyConnection As New Data.SqlClient.SqlConnection(MyDataSource.ConnectionString)
Dim cmdGetProducts As New Data.SqlClient.SqlCommand With cmdGetProducts
.Connection = MyConnection
.CommandType = Data.CommandType.Text
.CommandText = " SELECT * FROM XYZProducts WHERE ProductID=@ProductID "
. Parameters.AddWithValue("@ProductID", Request.QueryString("ProductID"))
End WithDim dsResults As New Data.DataSet Dim daDataAdapter As New Data.SqlClient.SqlDataAdapter(cmdGetProducts)daDataAdapter.Fill(dsResults, "GetProductDetailsQuery")
MyConnection.Open()MyConnection.Close()
cmdGetProducts = Nothing daDataAdapter = Nothing
Populate labels and Hidden Field with the Product Details
We are going to use a HiddenField control to store the ProductID for use if we need to addthe product to the cart.
Once the database operation is complete, hopefully we have found the product record wewish to display and it is sitting in our dataset object(dsResults) under our namedquery(GetProductDetailsQuery).
You will notice the first thing that happens in the code is that we use an If Else statement tocheck if there are any rows in dsResults.GetProductDetails. If the row count does not equal 0,
then the labels populate. If not, an error message is displayed to the user and we avoid acrash.
It is important that we never take for granted the presence of data in the database or we mayfind that our sites crash.
Immediately beneath the last chunk of code, enter the following:
If dsResults.Tables("GetProductDetailsQuery").Rows.Count 0 Then Me.imgProduct.ImageUrl = Server.MapPath("~/productimages/" &dsResults.Tables("GetProductDetailsQuery").Rows(0).Item("ProductID").ToString & ".jpg")
Me.lblProductName.Text =
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
36/119
page 36DIPLOMA PROGRAMMING 2009
dsResults.Tables("GetProductDetailsQuery").Rows(0).Item("ProductName")Me.lblDescription.Text =
dsResults.Tables("GetProductDetailsQuery").Rows(0).Item("Description")Me.lblPrice.Text =
dsResults.Tables("GetProductDetailsQuery").Rows(0).Item("Price")Else
Me.lblError.Visible = True Me.lblError.Text = "This product was not found. Please select another." hfPoductID.Value =dsResults.Tables("GetProductDetailsQuery").Rows(0).Item("ProductID")
End If
Run and test the project
FormatCurrency() method
You will notice that the price of our product is displaying as a simple decimal figure. It would bemuch better if we could display this value as currency.
Locate the line of code that sets the text property of lblPrice and modify it so it reads:
Me.lblPrice.Text = FormatCurrency(dsResults.Tables("GetProductDetailsQuery").Rows(0).Item("Price"))
Run and test the project
Where do we go from here?
OK, our website is now at the point where the user can choose to add the item to the cart. We arealso going to give them the option of returning to the list of products in the category they selected.
Let's work on the latter first.
You will recall we now have two active sessions - CategoryName and CategoryID . The categoryname session has been handy in that it has allowed us to display the category name on each page.The category ID will now also become handy because we are going to use it on productdetails.aspxif the user chooses to browse back to the list of products they came from.
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
37/119
page 37DIPLOMA PROGRAMMING 2009
Category Name LinkButton
When the user clicks this button, we are going to send them back to products.aspx with theCategoryID and CategoryName in a query string.
Why are we placing sessions in a query string? - Because the code on products.aspxthat gets the products from the database AND the code that places the CategoryName inthe label will be expecting to read the CategoryID and CategoryName from the querystring.
Got it? If your not sure, have a look right now. Enter the following code in the Click event of lnkCategoryName :
Response.Redirect("products.aspx?CategoryID=" & Session("CategoryID") &"&CategoryName=" & Session("CategoryName"))
Run and test the project
Page dependencies
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
38/119
page 38DIPLOMA PROGRAMMING 2009
You will find that many pages in your store will have dependencies - that is, they are pages thatcannot load until they are given some form of data such as a query string or access to a sessionvariable. products.aspx is one such page. It is dependant on the contents of the query stringcontaining the CategoryName and CategoryID.
You could try the following to watch products.aspx crash (a good demonstration of pagedependencies):
Comment out the code the code in the lnkCategoryName Click event and replace it with thefollowing:
Response.Redirect("products.aspx")
Run and test the project
Here's a screen shot of the error:
(Make sure you replace your original code after running this test.)
Add to cart
Now we will give our user the ability to add the item to the cart for purchase. But before we allowthem to do so, we are going to require them to select a quantity.
Select Quantity Add a DropDownList to productdetails.aspx and name it ddlQuantity
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
39/119
page 39DIPLOMA PROGRAMMING 2009
In the Items property click Add to add items 1 to 5 in the Text property. Leave the Value property as default. Shown below:
Note the index of each item position in the list beginning with 0.
Add To Cart Button Add a button to productdetails.aspx and call it btnAddToCart
Give the button a text property of "Add to cart"
Input Validation: Make sure the user has made a quantity selection before clicking
We are going to use an If Else statement to ensure that the user has made a selection from thequantity drop down list.
You will notice in the code below, the first line is checking that the SelectedIndex is greater that0. If you take another look at your drop down lost, you will see that the item with an Index of 0 isthe item that says "Select Quantity". Obviously we don't want to allow this selection because it isnot a quantity selection at all.
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
40/119
page 40DIPLOMA PROGRAMMING 2009
If the condition tests true (that an index greater than 0 was selected), we shoot the use off to thecart with the ProductID and the quantity in the query string.
If the condition does not test true , the statement jumps straight to the Else in which a warning isgiven to the user about selecting a quantity first.
Enter the following code in the Click event of btnAddToCart :
If ddlQuantity.SelectedIndex > 0 ThenResponse.Redirect("shoppingcart.aspx?ProductID=" & hfPoductID.Value.ToString &
"&Quantity=" & ddlQuantity.SelectedItem.ToString) Else
lblQuantityWarning.Visible = True End If
Run and test the project
Don't despair when you get the following error, it is just letting you know that it cannot findshoppingcart.aspx - which is fine because we haven't created it yet.
The most important thing to note at this point is the query string in the address bar. Boththe ProductID and the Quantity are present, ready for our INSERT operation.
Shown below:
Conclusion of Part 1
Ok, in part 2 we are going to build the shopping cart.
Edit this page (if you have permission) |
Google Docs -- Web word processing, presentations and spreadsheets.
Copyright Rachael Colley, 2009
http://docs.google.com/Edit?tab=edit&dr=true&docid=dfvxqtdd_159c84xvfr9http://docs.google.com/http://docs.google.com/Edit?tab=edit&dr=true&docid=dfvxqtdd_159c84xvfr9http://docs.google.com/8/14/2019 Diploma Programming 2009
41/119
page 41DIPLOMA PROGRAMMING 2009
Wednesday, March 4, 2009
Dip SEM 1 Week 4 PART 2 Tut Notes
Add a shopping cart Webform
Add a new webform to the project and call it shoppingcart.aspx
Remember to check the Select Master Page checkbox
Create new table XYZCart
Next we will create a table where cart items are added. Create a new table with the following fields and types:
Don't forget that CartID should have it's Identity property set to true!
If your wondering where all the fields are for product name, price etc dont! As long aswe have the ProductID saved, we can get any other info we need about the productwhen we need it. No point in clogging up 2 tables in the database with the same infoand this is a general rule of thumb.
We are not going to populate this table with any data because our application is going todo that for us.
So you may be wondering "Why are there no fields for things like product name andprice? Well, all we need to add for each cart item is the ProductID. As long as we havethe ProductID, we can get anything we need to know about the product from theproducts table. So thee is no point cluttering up our cart table with duplicate info.
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
42/119
page 42DIPLOMA PROGRAMMING 2009
Inface, this is general rule of thumb about duplication of data.
Cart Gridview
Initially, our cart gridview will display the product image, product name, unit price andquantity ordered. The product name will be rendered out in a HyperlinkField to enablethe user to go straight to the larger view of that product.
Return to shoppingcart.aspx and add a GridView called it gvCart
Open the Fields dialog and uncheck the Auto-Generate Fields checkbox
Add the following columns:
1. ImageField HeaderText: Image: DataImageURLField: ProductID DataImageURLFormatString: ~/productimages/{0}.jpg
2. HyperlinkField HeaderText: Item Name: DataNavigateURLFields: ProductID DataNavigateURLFormatString: ~/productdetails.aspx?ProductID={0} DataTextField: ProductName
3. BoundField HeaderText: Price: DataField: Price DataFormatString: {0:c}
4. BoundField
HeaderText: Quantity DataField: Quantity
Add To Cart Custom Procedure
We are going to create our own custom procedure that adds items to the cart. Switch to code view and create the procedure container on shoppingcart.aspx by
entering the following:
Private Sub AddToCart()
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
43/119
page 43DIPLOMA PROGRAMMING 2009
End Sub
Create a CustomerID
Each customer must have their own unique customer ID to ensure that each entryin the Cart table can be identified correctly.
There are many valid ways of creating a CustomerID. This how we are going tocreate it:
Randomize()Session("CustomerID") = Request.ServerVariables("REMOTE_HOST") & "-" &
Rnd.ToString
OK, the first line calls the Randomize() method. This method then initializes the randomnumber generator in VB.
The next line creates a session called "CustomerID" which is given a String value of theusers IP Address concatonated to the generated random number.
At run time, this string will look something like this: 127.0.0.1-0.1847956
This CustomerID session can then be added with item placed in the cart by the user.
Full Code listing for Private Sub AddToCart()
Private Sub AddToCart()
If Session("CustomerID") = "" ThenRandomize()Session("CustomerID") = Request.ServerVariables("REMOTE_HOST") & "-" &
Rnd.ToStringEnd If
Dim ConnectionStringLocation As ConnectionStringSettings =System.Configuration.ConfigurationManager.ConnectionStrings("Connstring")Dim ConnString As String = ConnectionStringLocation.ToStringDim MyDataSource As New SqlDataSource(ConnString, "")
Dim MyConnection As New Data.SqlClient.SqlConnection(MyDataSource.ConnectionString)
Dim cmdAddToCart As New Data.SqlClient.SqlCommand cmdAddToCart.CommandType = Data.CommandType.TextcmdAddToCart.Connection = MyConnection
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
44/119
page 44DIPLOMA PROGRAMMING 2009
cmdAddToCart.CommandText = "INSERT into XYZCart (CustomerID, ProductID,Quantity) VALUES (@CustomerID, @ProductID, @Quantity)" cmdAddToCart.Parameters.AddWithValue("@CustomerID", Session("CustomerID")) cmdAddToCart.Parameters.AddWithValue("@ProductID",Request.QueryString("ProductID")) cmdAddToCart.Parameters.AddWithValue("@Quantity",Request.QueryString("Quantity"))
MyConnection.Open()cmdAddToCart.ExecuteNonQuery()
MyConnection.Close()MyConnection = NothingcmdAddToCart = Nothing
End Sub
Checking for the presence of Session("CustomerID")
You will notice that the first thing that happens is that the code checks for the presence
of a session called "CustomerID". And I bet your thinking "But why? This is the first timethe user has added anything to the cart - ofcourse there is no CustomerID!". Well, thinka little further forward and you could well image that our customer may add severalitems to the cart, one after the other and we definatley do not want our codegenerating a new CustomerID each time or we will lose everything they have placed intheir cart!
So, if the If statement Can't find a session called "CustomerID" it will create one. If itdoes find one, it won't create a new one. Nice.
Loading/Refreshing the GridView with the customers items
Now that we have code that inserts stuff into the Cart table, we need our user to beable to see what they have added.
Create another custom procedure and call it RefreshCart
Here is the full code listing for the procedure, add this to shoppingcart.aspx :
Private Sub RefreshCart()
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
45/119
page 45DIPLOMA PROGRAMMING 2009
Dim ConnectionStringLocation As ConnectionStringSettings =System.Configuration.ConfigurationManager.ConnectionStrings("Connstring") Dim ConnString As String = ConnectionStringLocation.ToString
Dim MyDataSource As New SqlDataSource(ConnString, "")
Dim MyConnection As New Data.SqlClient.SqlConnection(MyDataSource.ConnectionString)
Dim cmdRefreshCart As New Data.SqlClient.SqlCommand cmdRefreshCart.CommandType = Data.CommandType.TextcmdRefreshCart.Connection = MyConnection
cmdRefreshCart.CommandText = " SELECT XYZCart.CartID, XYZCart.CustomerID, XYZCart.ProductID, XYZCart.Quantity, XYZProducts.ProductID, XYZProducts.CategoryID, XYZProducts.ProductName, XYZProducts.Description, XYZProducts.Price FROM XYZCart CROSS JOIN XYZProducts Where CustomerID=@CustomerID and XYZCart.ProductID=XYZProducts.ProductID " cmdRefreshCart.Parameters.AddWithValue("@CustomerID",Session("CustomerID"))
Dim dsResults As New Data.DataSet
Dim daGetAllAdapter As New Data.SqlClient.SqlDataAdapter(cmdRefreshCart)
daGetAllAdapter.Fill(dsResults, "GetCartQuery")
MyConnection.Open()MyConnection.Close()
MyConnection = NothingcmdRefreshCart = Nothing
If dsResults.Tables("GetCartQuery").Rows.Count 0 Then
Me.gvCart.DataSource = dsResultsMe.gvCart.DataMember = "GetCartQuery" Me.gvCart.DataKeyNames = New String() {"CartID"}Me.gvCart.DataBind()
Else
Me.lblCartWarning.Visible = True
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
46/119
page 46DIPLOMA PROGRAMMING 2009
me.gvCart.DataSource = Nothingme.gvCart.DataBind()
End If
End Sub
There is alot of stuff going on in that code. Let's go through it in point form: A Cross Join is a special type of join used in SQL programming to join records from
two or more related tables. We needed info from the cart table AND the productstable for a particular user and a particular product and that is exactly what we willget with this rather long SQL statement.
Incidently, what a great blog topic for you guys - SQL JOINS. Just an idea.
After the database operation has run, we run an If statement to check if any rows(records) were returned to the dataset. If the row count is greater than 0 then weallow the Gridview to databind. If not, we display a message to the user, warningthem that they have no items in the cart (You better add that label too -lblCartWarning, visible: False, Text: You have not items in your cart).
Run and test the project
Nothing happens - huh?
That's because we have not called the AddToCart and RefreshCart procedures solet's do so in the Load event of shoppingcart.aspx :
If Not Page.IsPostBack Then
AddToCart() RefreshCart()End If
Now try it!
Conclusion to Part 2
In the next part we will be adding some groovy stuff that allows the user to modify thecontents of their cart and also things like sub totals, GST, shipping etc. Stay toooooned.
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
47/119
page 47DIPLOMA PROGRAMMING 2009
Edit this page (if you have permission) | Google Docs -- Web word processing, presentations and spreadsheets.
Thursday, March 5, 2009
Page dependencies You will find that many pages in your store will have dependencies - that is, they are pages thatcannot load until they are given some form of data such as a query string or access to a sessionvariable. products.aspx in our OnlineStore is one such page. It is dependant on the contents of thequery string containing the CategoryName and CategoryID.
Go back and look at the code.
Posted by RSColley at 11:49 AM 0 comments Links to this post Labels: Page dependencies , QueryString , sessions
FormatCurrency() method Use the FormatCurrency() method to format data as currency.
Example from productdetails.aspx:
lblPrice.Text = FormatCurrency(dsResults.Tables("GetProductDetailsQuery").Rows(0).Item("Price"))
What if we need to format currency in a gridview?
Modify the DataFormatString property of the column to the following:
{0:c}
Copyright Rachael Colley, 2009
http://docs.google.com/Edit?tab=edit&dr=true&docid=dfvxqtdd_181gt89ktf4http://docs.google.com/http://diplomaprogramming.blogspot.com/2009/03/page-dependencies.htmlhttp://diplomaprogramming.blogspot.com/2009/03/page-dependencies.htmlhttp://diplomaprogramming.blogspot.com/2009/03/page-dependencies.html#commentshttp://diplomaprogramming.blogspot.com/2009/03/page-dependencies.html#commentshttp://diplomaprogramming.blogspot.com/2009/03/page-dependencies.html#linkshttp://diplomaprogramming.blogspot.com/search/label/Page%20dependencieshttp://diplomaprogramming.blogspot.com/search/label/QueryStringhttp://diplomaprogramming.blogspot.com/search/label/QueryStringhttp://diplomaprogramming.blogspot.com/search/label/sessionshttp://diplomaprogramming.blogspot.com/2009/03/formatcurrency-method.htmlhttp://www.blogger.com/post-edit.g?blogID=563724260557473738&postID=2448538413733841524http://www.blogger.com/email-post.g?blogID=563724260557473738&postID=2448538413733841524http://docs.google.com/Edit?tab=edit&dr=true&docid=dfvxqtdd_181gt89ktf4http://docs.google.com/http://diplomaprogramming.blogspot.com/2009/03/page-dependencies.htmlhttp://diplomaprogramming.blogspot.com/2009/03/page-dependencies.htmlhttp://diplomaprogramming.blogspot.com/2009/03/page-dependencies.html#commentshttp://diplomaprogramming.blogspot.com/2009/03/page-dependencies.html#linkshttp://diplomaprogramming.blogspot.com/search/label/Page%20dependencieshttp://diplomaprogramming.blogspot.com/search/label/QueryStringhttp://diplomaprogramming.blogspot.com/search/label/sessionshttp://diplomaprogramming.blogspot.com/2009/03/formatcurrency-method.html8/14/2019 Diploma Programming 2009
48/119
page 48DIPLOMA PROGRAMMING 2009
BoundColumn.DataFormatString Property -http://authors.aspalliance.com/aspxtreme/sys/web/ui/webcontr ols/BoundColumnClassDataFormatString.aspx
BoundField..::.DataFormatString Property - http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.boundfield.dataformatstring.aspx
Posted by RSColley at 11:19 AM 1 comments Links to this post Labels: FormatCurrency() method , GridView
Hidden Fields Sometimes storing data in hiddden fields on a page is handy. It's just like having an invisible label.
In our OnlineShopping project, so far we have used a Hidden Field to on productdetails.aspx tostore our ProductID on the page.
We populated the label from the dataset in the following way:
hfProductID.Value = dsResults.Tables("GetProductDetailsQuery").Rows(0).Item("ProductID")
When the user clicked to Add To Cart, we placed the ProductID in the Hidden Field into a querystring:
Response.Redirect("shoppingcart.aspx?ProductID=" & hfProductID.Value.ToString &"&Quantity=" & ddlQuantity.SelectedItem.ToString)
Could we have used a session? Sure! Why didn't we? As the data was only required from one pageto the next, a session seemed a little excessive.
Posted by RSColley at 11:09 AM 0 comments Links to this post Labels: Hidden Fields , QueryString , sessions
Product images for your assignment For the purposes of this assignment, product images should be jpg files and each should be namedafter the corresponding product ProductID.
An important thing to note when creating product images for your store: make sure each image is asquare. This will ensure that they render out in a predictable fashion.
Copyright Rachael Colley, 2009
http://diplomaprogramming.blogspot.com/BoundColumn.DataFormatString%20Propertyhttp://diplomaprogramming.blogspot.com/BoundColumn.DataFormatString%20Propertyhttp://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.boundfield.dataformatstring.aspxhttp://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.boundfield.dataformatstring.aspxhttp://diplomaprogramming.blogspot.com/2009/03/formatcurrency-method.htmlhttp://diplomaprogramming.blogspot.com/2009/03/formatcurrency-method.html#commentshttp://diplomaprogramming.blogspot.com/2009/03/formatcurrency-method.html#commentshttp://diplomaprogramming.blogspot.com/2009/03/formatcurrency-method.html#linkshttp://diplomaprogramming.blogspot.com/search/label/FormatCurrency()%20methodhttp://diplomaprogramming.blogspot.com/search/label/FormatCurrency()%20methodhttp://diplomaprogramming.blogspot.com/search/label/GridViewhttp://diplomaprogramming.blogspot.com/2009/03/hidden-fields.htmlhttp://diplomaprogramming.blogspot.com/2009/03/hidden-fields.htmlhttp://diplomaprogramming.blogspot.com/2009/03/hidden-fields.html#commentshttp://diplomaprogramming.blogspot.com/2009/03/hidden-fields.html#commentshttp://diplomaprogramming.blogspot.com/2009/03/hidden-fields.html#linkshttp://diplomaprogramming.blogspot.com/search/label/Hidden%20Fieldshttp://diplomaprogramming.blogspot.com/search/label/QueryStringhttp://diplomaprogramming.blogspot.com/search/label/sessionshttp://diplomaprogramming.blogspot.com/2009/03/product-images-for-your-assignment.htmlhttp://www.blogger.com/post-edit.g?blogID=563724260557473738&postID=5371082952472753721http://www.blogger.com/email-post.g?blogID=563724260557473738&postID=5371082952472753721http://www.blogger.com/post-edit.g?blogID=563724260557473738&postID=4898086191543348890http://www.blogger.com/email-post.g?blogID=563724260557473738&postID=4898086191543348890http://diplomaprogramming.blogspot.com/BoundColumn.DataFormatString%20Propertyhttp://diplomaprogramming.blogspot.com/BoundColumn.DataFormatString%20Propertyhttp://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.boundfield.dataformatstring.aspxhttp://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.boundfield.dataformatstring.aspxhttp://diplomaprogramming.blogspot.com/2009/03/formatcurrency-method.htmlhttp://diplomaprogramming.blogspot.com/2009/03/formatcurrency-method.html#commentshttp://diplomaprogramming.blogspot.com/2009/03/formatcurrency-method.html#linkshttp://diplomaprogramming.blogspot.com/search/label/FormatCurrency()%20methodhttp://diplomaprogramming.blogspot.com/search/label/GridViewhttp://diplomaprogramming.blogspot.com/2009/03/hidden-fields.htmlhttp://diplomaprogramming.blogspot.com/2009/03/hidden-fields.htmlhttp://diplomaprogramming.blogspot.com/2009/03/hidden-fields.html#commentshttp://diplomaprogramming.blogspot.com/2009/03/hidden-fields.html#linkshttp://diplomaprogramming.blogspot.com/search/label/Hidden%20Fieldshttp://diplomaprogramming.blogspot.com/search/label/QueryStringhttp://diplomaprogramming.blogspot.com/search/label/sessionshttp://diplomaprogramming.blogspot.com/2009/03/product-images-for-your-assignment.html8/14/2019 Diploma Programming 2009
49/119
page 49DIPLOMA PROGRAMMING 2009
Week 5 Part 1 Tut notes
DIP Sem 1 Week 5 Part 1 Tut Notes
Now it's time to add some more functionality to our cart.
Increase quantity of items Decrease quantity of items Remove items from cart Display the total for each item Display the sub total of all items Display total of shipping
Calculate and display GST Calculate and display Total Payable
Modify the GridView
We are going to use some additional fields in our GridView called TemplateFields . When you need tocreate custom behaviours and content that the standard GridView fields can't handle, use aTemplateField .
Create Button Images We are going to provide the user with Increase, Decrease & Remove ImageButtons for each item in thecart.
Create a folder in your site called buttonimages
Create Increase.gif (approx 30x30px)
Create Decrease.gif (approx 30x30px)
Create.Remove.gif (approx 30x30px)
Add the button images to the buttonimages folder of your website
On shoppingcart.aspx, open the Fields dialog of gvShoppingCart
Copyright Rachael Colley, 2009
http://diplomaprogramming.blogspot.com/2009/03/week-5-part-1-tut-notes.htmlhttp://diplomaprogramming.blogspot.com/2009/03/week-5-part-1-tut-notes.html8/14/2019 Diploma Programming 2009
50/119
page 50DIPLOMA PROGRAMMING 2009
Create TemplateFields
In this section we will create the TempateFields required in the GridView.
Create a TemplateField for Increase
Select a ButtonField and click Add
Enter " Increase " in the HeaderText property
Locate the link text at the bottom of the dialog that says Convert this field into a TemplateFieldand click it.
Create a TemplateField for Decrease
Select a ButtonField and click Add
Enter " Decrease " in the HeaderText property
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
51/119
page 51DIPLOMA PROGRAMMING 2009
Locate the link text at the bottom of the dialog that says Convert this field into a TemplateField
and click it.
Create a TemplateField for Remove
Select a ButtonField and click Add
Enter " Remove " in the HeaderText property
Locate the link text at the bottom of the dialog that says Convert this field into a TemplateFieldand click it.
Create a TemplateField for Total
Select a BoundField and click Add
Enter " Total " in the HeaderText property
Locate the link text at the bottom of the dialog that says Convert this field into a TemplateFieldand click it.
The Selected Fields in your GridView should now look like this:
Click Ok and return to design view
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
52/119
page 52DIPLOMA PROGRAMMING 2009
Click the small arrow on the edge of the GridView to open the GridView Tasks menu
Select the Edit Templates option
Edit the TemplateFields
Now we are going to edit the properties of each of the TemplateFields we have created.
Edit 'Increase' TemplateField From the Display drop down list, select Increase
Your view should now look something like the screenshot below.
From the section called ItemTemplate , delete the button and replace it with an ImageButtonfrom the toolbox
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
53/119
page 53DIPLOMA PROGRAMMING 2009
With the ImageButton selected, modify the following properties:
Name : imgbtnIncrease CommandName : Increase ImageURL : ~/buttonimages/btnIncrease.gif
Click the small arrow on the edge of the imgbtnIncrease to open the ImageButton Tasks menu andselect Edit Databingdings
From the Bindable Properties list on the left, select CommandArgument
On the lower right, enter the following into the code expression textbox:
Bind("CartID")
It should look like the screenshot below.
Click OK
Edit 'Decrease' TemplateField
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
54/119
page 54DIPLOMA PROGRAMMING 2009
Make sure you are still in TemplateEditing mode and from the Display drop down list, selectDecrease
From the section called ItemTemplate , delete the button and replace it with an ImageButtonfrom the toolbox
With the ImageButton selected, modify the following properties:
Name : imgbtnDecrease CommandName : Decrease ImageURL : ~/buttonimages/btnDecrease.gif
Click the small arrow on the edge of the imgbtnDecrease to open the ImageButton Tasks menuand select Edit Databingdings
From the Bindable Properties list on the left, select CommandArgument
On the lower right, enter the following into the code expression textbox:
Bind("CartID")
Click OK
Edit 'Remove' TemplateField Make sure you are still in TemplateEditing mode and from the Display drop down list, select
Remove
From the section called ItemTemplate , delete the button and replace it with an ImageButtonfrom the toolbox
With the ImageButton selected, modify the following properties:
Name : imgbtnRemove CommandName : Remove ImageURL : ~/buttonimages/btnRemove.gif
Click the small arrow on the edge of the imgbtnRemove to open the ImageButton Tasks menu andselect Edit Databindings
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
55/119
page 55DIPLOMA PROGRAMMING 2009
From the Bindable Properties list on the left, select CommandArgument
On the lower right, enter the following into the code expression textbox:
Bind("CartID")
Click OK
Edit 'Total' TemplateField Make sure you are still in TemplateEditing mode and from the Display drop down list, select
Remove
From the section called ItemTemplate , rename the label lblItemTotal
Click OK
From the GridView Tasks menu, select End Template Editing
In Conclusion
When the user clicks Increase, Decrease or Remove buttons in the GridView, we need to updatethe Cart table in the database.
You would have noticed that each of our buttons have a CommandName property and aCommandArgument property (if you are unsure, go back and have a look at the properties of each button).
When we give an object a CommandName , we can watch for that Command call in the Commandevent of the parent control - OR - to put it simply, if a control in the GridView with aCommandName of Increase is clicked, we can capture that event in the RowCommand event of the GridView and execute code accordingly.
What is the CommandArgument ? You will recall that an argument is a value that is passed to amethod. We have databound each buttons CommandArgument to the feild CartID . So, in this
case, when the user clicks one of the buttons, we want to pass the CartID of the corresponding item
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
56/119
page 56DIPLOMA PROGRAMMING 2009
to the RowCommand event.
Edit this page (if you have permission) | Google Docs -- Web word processing, presentations and spreadsheets.
Week 5 Part 2 Tut notesDip Sem 1 Week 5 Part 2 Tut Notes
Code the Increase, Decrease & Remove buttons in the GridView.RowCommand event
I'll repeat what I said at the conclusion of last tut notes:
When the user clicks Increase, Decrease or Remove buttons in the GridView, we need to updatethe Cart table in the database.
You would have noticed that each of our buttons have a CommandName property and aCommandArgument property (if you are unsure, go back and have a look at the properties of each button).
When we give an object a CommandName , we can watch for that Command call in the Commandevent of the parent control - OR - to put it simply, if a control in the GridView with aCommandName of Increase is clicked, we can capture that event in the RowCommand event of the GridView and execute code accordingly.
What is the CommandArgument ? You will recall that an argument is a value that is passed to amethod. We have databound each buttons CommandArgument to the feild CartID . So, in thiscase, when the user clicks one of the buttons, we want to pass the CartID of the corresponding itemto the RowCommand event.
Capture the CartID of the Cart item being modified
Enter the following code in the RowCommand event of shoppingcart.aspx :
Dim intCartItemID As Integer = e.CommandArgument
In this step we create an integer variable to hold the value of the CommandArgument contained in
Copyright Rachael Colley, 2009
http://docs.google.com/Edit?tab=edit&dr=true&docid=dfvxqtdd_186cjq6qqc8http://docs.google.com/http://diplomaprogramming.blogspot.com/2009/03/week-2-part-2-tut-notes.htmlhttp://docs.google.com/Edit?tab=edit&dr=true&docid=dfvxqtdd_186cjq6qqc8http://docs.google.com/http://diplomaprogramming.blogspot.com/2009/03/week-2-part-2-tut-notes.html8/14/2019 Diploma Programming 2009
57/119
page 57DIPLOMA PROGRAMMING 2009
the sender of the Command ( e). You will recall that the CommandArgument of each of our buttonsis the CartID associated with the row or cart item.
For example, if the cart item being modified has a CartID of 24, our integer variable now has avalue of 24. It is important to capture this ID because we need it to perform the database operationon the correct cart item.
Declare database objects for the operation Immediatley beneath the last line of code, enter the following code to create our database
objects:
Dim ConnectionStringLocation As ConnectionStringSettings =System.Configuration.ConfigurationManager.ConnectionStrings("Connstring")
Dim ConnString As String = ConnectionStringLocation.ToString Dim MyDataSource As New SqlDataSource(ConnString, "")
Dim MyConnection As New Data.SqlClient.SqlConnection(MyDataSource.ConnectionString)Dim cmdChangeCart As New Data.SqlClient.SqlCommand cmdChangeCart.CommandType = Data.CommandType.Text cmdChangeCart.Connection = MyConnection
In the next steps we will use If statements to check the CommandName being called from theGridView. Based upon the result, the appropriate database command will be used in the operation.
Add If statement to check if the CommandName being called is " Increase "
If e.CommandName = " Increase " ThencmdChangeCart.CommandText = " UPDATE XYZCart SET Quantity=Quantity + 1 where
CartID=@CartID"cmdChangeCart.Parameters.AddWithValue("@CartID", intCartItemID)
End If
This database command will be used if the CommandName is " Increase ".
Notice that this an Update statement. The quantity for the item will be incremented by 1 (Quantity= Quantity + 1) but only for the record with the specified CartID (WHERE CartID=@CartID).
Add If statement to check if the CommandName being called is " Decrease "
If e.CommandName = "Decrease" Then
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
58/119
page 58DIPLOMA PROGRAMMING 2009
cmdChangeCart.CommandText = " UPDATE XYZCart SET Quantity=Quantity - 1 whereCartID=@CartID and Quantity>1 "
cmdChangeCart.Parameters.AddWithValue("@CartID", intCartItemID)End If
This database command will be used if the CommandName is " Decrease ".
Notice that this is also an Update statement. The quantity for the item will be deducted by 1(Quantity = Quantity - 1) but only for the record with the specified CartID (WHERECartID=@CartID).
There is an additional part to this UPDATE statement , notice that the very last part of thestatement specifies and Quantity>1. This is to ensure that the quantity is only deducted by 1 if thecurrent quantity is greater than 1. We certainly do not want items with 0 quantity in our cart or itemswith negative (-1) quantities.
Add If statement to check if the CommandName being called is " Remove "
If e.CommandName = " Remove " ThencmdChangeCart.CommandText = " DELETE from XYZCart where CartID=@CartID " cmdChangeCart.Parameters.AddWithValue("@CartID", intCartItemID)
End If
This database command will be used if the CommandName is " Remove ".
Notice that this is a Delete statement. The cart item with the specified CartID (WHERECartID=@CartID) is deleted.
Finish coding database operation objects
MyConnection.Open()
cmdChangeCart.ExecuteNonQuery() MyConnection.Close()
MyConnection = Nothing cmdChangeCart = Nothing
Call the RefreshCart sub
RefreshCart()
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
59/119
page 59DIPLOMA PROGRAMMING 2009
Remember, each time we make a change to the database, we need to refresh our view of the records.
Full code listing for the RowCommand event of gvCart:
Dim intCartItemID As Integer = e.CommandArgument
Dim ConnectionStringLocation As ConnectionStringSettings =System.Configuration.ConfigurationManager.ConnectionStrings("Connstring")
Dim ConnString As String = ConnectionStringLocation.ToString Dim MyDataSource As New SqlDataSource(ConnString, "")
Dim MyConnection As New Data.SqlClient.SqlConnection(MyDataSource.ConnectionString)Dim cmdChangeCart As New Data.SqlClient.SqlCommand cmdChangeCart.CommandType = Data.CommandType.Text cmdChangeCart.Connection = MyConnection
If e.CommandName = "Increase" ThencmdChangeCart.CommandText = "UPDATE XYZCart SET Quantity=Quantity + 1 where
CartID=@CartID" cmdChangeCart.Parameters.AddWithValue("@CartID", intCartItemID)
End If
If e.CommandName = "Decrease" ThencmdChangeCart.CommandText = "UPDATE XYZCart SET Quantity=Quantity - 1 where
CartID=@CartID and Quantity>1" cmdChangeCart.Parameters.AddWithValue("@CartID", intCartItemID)
End If
If e.CommandName = "Remove" ThencmdChangeCart.CommandText = "DELETE from XYZCart where CartID=@CartID" cmdChangeCart.Parameters.AddWithValue("@CartID", intCartItemID)
End If
MyConnection.Open()cmdChangeCart.ExecuteNonQuery()MyConnection.Close()
MyConnection = Nothing cmdChangeCart = Nothing
RefreshCart()
Copyright Rachael Colley, 2009
8/14/2019 Diploma Programming 2009
60/119
page 60DIPLOMA PROGRAMMING 2009
Run and test project
Modify quantities in the cart
In conclusion
Now our user can manipulate the items in the cart. In the next step we will start calculating totals.
Edit this page (if you have permission) | Google Docs -- Web word processing, presentations and spreadsheets.
Week 5 Part 3 Tut notesDIP sem 1 Week 5 Part 3 Tut Notes
Finding items in the GridView
Often we need to find an item inside of a GridView control. For instance, in the nextsection, we are going to calculate a total for each item (quantity x price) in theGridView. Remember, we have not recorded any totals in the database, we are going toprogrammaticaly generate totals on the fly.