Introduction
This article will guide you to create ShoppingCart using Gridview in ASP.net with code VB.
Background
I have succeeded in creating a shopping cart use GridView combination Session . Everyone knows Session has huge storage capacity,
make use of it in this work . Although this issue has been many people do, but you can compare my post to them. You will see the difference.
Using the code
Operation process is described as follows: First created ShoppingCart using DataTable , then saved to the session variable.
Session variables will keep your cart during work .Default when a user login successfull , the Shoppingcart will create, by contrast does not create.
Sub CreateShopCart()
Dim dt As New DataTable
If dt.TableName.Contains("tblShopCart") = True Then //check tblShopCart have not use
Exit Sub
Else
dt = New DataTable("tblShopCart") //create new tblshopcart
dt.Columns.Add("proid", GetType(Integer))
dt.Columns.Add("proname", GetType(String))
dt.Columns.Add("number", GetType(Integer))
dt.Columns.Add("price", GetType(Double))
dt.Columns.Add("total", GetType(Double))
End If
Session("ShopCart") = dt //save tblshopcart into Session variable
End Sub
When login is successful, users will go shopping, when the user clicks a purchase, we will have Sub Addtocart().
The main of this sub is to add a row to Session("shopcart"), check if the product is then automatically increase
the amount of a product. and this shopcart is in the Session variable.
Sub AddToCart()
Dim dt As DataTable = Session("ShopCart")
If dt.Rows.Count <= 0 Then
Dim dr As DataRow = dt.NewRow
dr("proid") = Request("proid")
dr("proname") = lb_proname.Text
dr("number") = 1
dr("price") = lb_proprice.Text
dr("total") = dr("number") * dr("price")
dt.Rows.Add(dr)
Session("ShopCart") = dt
Exit Sub
Else
For i As Integer = 0 To dt.Rows.Count - 1
If dt.Rows(i)("proid") = Request("proid") Then
dt.Rows(i)("number") += 1
dt.Rows(i)("total") = dt.Rows(i)("number") * dt.Rows(i)("price")
Session("ShopCart") = dt
Exit Sub
End If
Next
Dim dr As DataRow = dt.NewRow
dr("proid") = Request("proid")
dr("proname") = lb_proname.Text
dr("number") = 1
dr("price") = lb_proprice.Text
dr("total") = dr("number") * dr("price")
dt.Rows.Add(dr)
Session("ShopCart") = dt
Exit Sub
End If
End Sub
When users see more details on shopping cart, you will need to bind data from Session ("Shopcart") to GridView. On this Girdview,
I will let the user can adjust the amount shopcart as edit or delete
<asp:GridView ID="gv_shopcart" runat="server" AutoGenerateColumns="False"
DataKeyNames="proid" ShowFooter="True"
ShowHeaderWhenEmpty="True"
EmptyDataText=" Not product in shopping cart "
EmptyDataRowStyle-ForeColor="Red" GridLines="None">
<HeaderStyle BackColor="LightCyan" ForeColor="MediumBlue" />
<FooterStyle BorderStyle="Groove" BorderWidth="1"
BackColor="LightCyan" ForeColor="MediumBlue" />
<Columns>
<asp:BoundField DataField="proid" FooterText="Total Bill"
HeaderText="Pro ID" ReadOnly="True">
<FooterStyle HorizontalAlign="Center" />
<HeaderStyle BorderStyle="Groove" BorderWidth="1px" HorizontalAlign="Center" />
<ItemStyle BorderStyle="Groove" BorderWidth="1px" HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="proname" HeaderText="ProName" ReadOnly="True">
<HeaderStyle BorderStyle="Groove" BorderWidth="1px" HorizontalAlign="Center" />
<ItemStyle BorderStyle="Groove" BorderWidth="1px" HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="number" HeaderText="Number">
<HeaderStyle BorderStyle="Groove" BorderWidth="1px" HorizontalAlign="Center" />
<ItemStyle BorderStyle="Groove" BorderWidth="1px" HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="price" HeaderText="Price" ReadOnly="True">
<HeaderStyle BorderStyle="Groove" BorderWidth="1px" HorizontalAlign="Center" />
<ItemStyle BorderStyle="Groove" BorderWidth="1px" HorizontalAlign="Center" />
</asp:BoundField>
<asp:TemplateField HeaderText="Total Price">
<HeaderStyle BorderStyle="Groove" BorderWidth="1px" HorizontalAlign="Center" />
<ItemStyle BorderStyle="Groove" BorderWidth="1px" HorizontalAlign="Center" />
<ItemTemplate>
<asp:Label ID="lb_prototal" runat="server"
Text='<%#Eval("total") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lb_totalbill" runat="server"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Image"
CancelImageUrl="~/Image/cancel.png"
DeleteImageUrl="~/Image/delete.png"
EditImageUrl="~/Image/edit.png" HeaderText="Option"
ShowDeleteButton="True" ShowEditButton="True"
UpdateImageUrl="~/Image/ok.png">
<HeaderStyle BorderStyle="Groove" BorderWidth="1px" HorizontalAlign="Center" />
<ItemStyle BorderStyle="Groove" BorderWidth="1px" HorizontalAlign="Center" />
</asp:CommandField>
</Columns>
</asp:GridView>
// this is VB code Cart.aspx.vb
Sub load_cart()
If Session("ShopCart") Is Nothing Then
gv_shopcart.DataSource = ""
gv_shopcart.DataBind()
Else
gv_shopcart.DataSource = Session("ShopCart")
gv_shopcart.DataBind()
End If
End Sub
Protected Sub gv_shopcart_RowCancelingEdit(ByVal sender As Object, ByVal e As _
System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles gv_shopcart.RowCancelingEdit
gv_shopcart.EditIndex = -1
load_cart()
End Sub
Protected Sub gv_shopcart_RowDataBound(ByVal sender As Object, ByVal e As _
System.Web.UI.WebControls.GridViewRowEventArgs) Handles gv_shopcart.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim price As Double = 0.0
Double.TryParse(e.Row.Cells(4).Text, price)
priceTotal += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "total"))
End If
If e.Row.RowType = DataControlRowType.Footer Then
Dim lbtotalbill As Label = DirectCast(e.Row.FindControl("lb_totalbill"), Label)
lbtotalbill.Text = priceTotal.ToString("c")
End If
End Sub
Protected Sub gv_shopcart_RowDeleting(ByVal sender As Object, ByVal e As _
System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles gv_shopcart.RowDeleting
Dim dt As DataTable = Session("ShopCart")
If dt.Rows.Count <= 0 Then
load_cart()
Else
dt.Rows(e.RowIndex).Delete()
dt.AcceptChanges()
Session("ShopCart") = dt
load_cart()
End If
End Sub
Protected Sub gv_shopcart_RowEditing(ByVal sender As Object, ByVal e _
As System.Web.UI.WebControls.GridViewEditEventArgs) Handles gv_shopcart.RowEditing
gv_shopcart.EditIndex = e.NewEditIndex
load_cart()
End Sub
Protected Sub gv_shopcart_RowUpdating(ByVal sender As Object, ByVal e As _
System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles gv_shopcart.RowUpdating
Dim dt As DataTable = Session("ShopCart")
Dim txt_number As TextBox = gv_shopcart.Rows(e.RowIndex).Cells(2).Controls(0)
Dim reg_exp As New Regex("^\d+$")
Dim arow As GridViewRow = gv_shopcart.Rows(e.RowIndex)
If Not reg_exp.IsMatch(DirectCast(arow.Cells(2).Controls(0), TextBox).Text) Then
DirectCast(arow.Cells(2).Controls(0), TextBox).Text = "Only number positive"
DirectCast(arow.Cells(2).Controls(0), TextBox).ForeColor = Drawing.Color.Red
e.Cancel = True
Else
Dim number_pro As Integer = Integer.Parse(txt_number.Text)
If number_pro = 0 Then
dt.Rows(e.RowIndex).Delete()
dt.AcceptChanges()
Session("ShopCart") = dt
load_cart()
Else
dt.Rows(e.RowIndex)("number") = number_pro
dt.Rows(e.RowIndex)("total") = dt.Rows(e.RowIndex)("price") * dt.Rows(e.RowIndex)("number")
dt.AcceptChanges()
Session("ShopCart") = dt
gv_shopcart.EditIndex = -1
load_cart()
End If
End If
End Sub
Demo
You can see it at: http://www.youtube.com/watch?v=fygTXk7_wHQ
Note
To check the work process, I should remind you to change the name server in the web.config file of the project
<appSettings>
<add key="stringconnect"
value="server=You change name your Server in here ;database=ShopCart ; integrated security=true"/>
</appSettings>