ASP.NET GridView Control and Shopping Cart Cookies
ASP.NET GridView Control
The ASP.NET GridView server control is a server-side rich-data control for repeated-value binding. It is the successor to the .NET Framework version 1.1 DataGrid control.
The GridView is a powerful control that provides the ability to display, format, paginate, and edit data.
Cookies in ASP.NET
Cookies are pieces of information generated by a web server and stored in the user’s computer for future access. They are embedded in the HTTP header information flowing back and forth between the user’s computer and a web server.
Types of Cookies
- Temporary/Session Cookies: Exist only in the browser’s memory and are never stored on disk. When the browser is closed, all temporary cookies are lost.
- Persistent Cookies: Stored on disk and can survive indefinitely.
Shopping Cart Example
Below is an example of adding items to a shopping cart using ASP.NET and cookies:
ShoppingCart Class
Public Class ShoppingCart
Public Shared Sub AddItemToCart(ByVal ProductCode As String, ByVal Quantity As Integer)
ProductCode = ProductCode.Trim
If ProductCode.Length > 0 Then
If Quantity > 0 Then
Dim Cart As DataSet = RetrieveCart()
Dim NewItem As DataRow = Cart.Tables.Item("Items").NewRow
'The column names have been shortened to P and Q to reduce the size of the XML to allow more entries because cookies are limited in size.
With NewItem
.Item("P") = ProductCode
.Item("Q") = Quantity
End With
Cart.Tables.Item("Items").Rows.Add(NewItem)
Dim CartXML As New System.Text.StringBuilder
Dim CartXMLStream As New System.IO.StringWriter(CartXML)
Cart.WriteXml(CartXMLStream)
Dim XML As New System.Text.StringBuilder
'Strip control characters and whitespace to reduce cookie size.
For I As Integer = 0 To CartXML.Length - 1
Dim C As Char = CartXML.Chars(I)
If Not (Char.IsControl(C) Or Char.IsWhiteSpace(C)) Then
XML.Append(C)
End If
Next
HttpContext.Current.Response.Cookies.Add(New HttpCookie("ShoppingCart", ToEncodedCookie(XML.ToString())))
End If
Else
Throw New Exception("A ProductCode must be supplied.")
End If
End SubPublic Shared Function RetrieveCart() As DataSet
'Implementation for retrieving the cart
End Function'Other methods for the ShoppingCart class
End Class