Click here to Skip to main content
11,639,554 members (63,230 online)
Click here to Skip to main content

ShoppingCart using Gridview in ASP.NET

, 13 Jun 2012 CPOL 39.9K 3.4K 7
Rate this:
Please Sign up or sign in to vote.
How to create ShoppingCart using Gridview in asp.net with code VB

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>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

headshot9x
Web Developer
Vietnam Vietnam
If you have a questions, you can contact me via e-mail address : headshot9x9@gmail.com (I regularly check email )

Address 1: Lac Hong University, Buu Long Ward - Bien Hoa City, Dong Nai Province, Vietnam Country
Or Address 2 : 141B2, Tan Phong ward, Bien Hoa City, Dong Nai Province, Vietnam Country
I've had more than two years experience asp.net programmer using VB, SQL Server, have knowledge of PHP + MySQL, HTML, Crystal Report, AJAX, etc ... and Windows Form programming.

You may also be interested in...

Comments and Discussions

 
QuestionStore Procedure Pin
Hessam Mir Tabatabaee14-Jul-15 0:17
memberHessam Mir Tabatabaee14-Jul-15 0:17 
QuestionUser Identification prior to shopping Pin
Member 112812643-Dec-14 11:13
memberMember 112812643-Dec-14 11:13 
AnswerRe: User Identification prior to shopping Pin
headshot9x23-Mar-15 0:24
memberheadshot9x23-Mar-15 0:24 
GeneralStore Procedure Please Pin
jose alberto lujan huachhuaco4-Nov-14 15:10
memberjose alberto lujan huachhuaco4-Nov-14 15:10 
GeneralStored Procedures Pin
Member 1065730612-Mar-14 23:02
memberMember 1065730612-Mar-14 23:02 
QuestionC# code Pin
Member 1058794711-Feb-14 1:29
memberMember 1058794711-Feb-14 1:29 
AnswerRe: C# code Pin
thatraja27-Feb-14 1:29
protectorthatraja27-Feb-14 1:29 
AnswerRe: C# code Pin
ghatiya27-Apr-14 21:05
memberghatiya27-Apr-14 21:05 
QuestionWhat is 'errcode' in the Login.aspx page and where is this found? Pin
Rick Lister11-Feb-13 4:48
memberRick Lister11-Feb-13 4:48 
QuestionI m getting some prob Please Help Pin
Shashangka_Shekhar15-Jan-13 8:06
memberShashangka_Shekhar15-Jan-13 8:06 
AnswerRe: I m getting some prob Please Help Pin
headshot9x15-Jan-13 14:47
memberheadshot9x15-Jan-13 14:47 
GeneralRe: I m getting some prob Please Help Pin
samflex27-Aug-14 3:39
membersamflex27-Aug-14 3:39 
QuestionRegarding Shopping Cart Pin
Sumit_Kumar_Sinha17-Oct-12 23:33
memberSumit_Kumar_Sinha17-Oct-12 23:33 
AnswerRe: Regarding Shopping Cart Pin
headshot9x18-Oct-12 0:59
memberheadshot9x18-Oct-12 0:59 
GeneralMy vote of 5 Pin
headshot9x13-Jun-12 15:51
memberheadshot9x13-Jun-12 15:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150731.1 | Last Updated 13 Jun 2012
Article Copyright 2012 by headshot9x
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid