Click here to Skip to main content
15,898,134 members
Articles / Web Development / ASP.NET
Tip/Trick

ShoppingCart using Gridview in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.60/5 (4 votes)
13 Jun 2012CPOL1 min read 105.8K   4.4K   7   27
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.

ASP.NET
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.

VB
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.NET
<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>
VB
// 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  

ASP.NET
<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)


Written By
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 and C#, SQL Server and Oracle, have knowledge of PHP + MySQL, HTML, CSS, Javascript, Jquery, AJAX, AngularJS, MVC, Webservices, etc ... and Windows Form programming.

Comments and Discussions

 
QuestionShopping cart in asp.net vb Pin
Member 1314501422-Apr-17 3:24
Member 1314501422-Apr-17 3:24 
AnswerRe: Shopping cart in asp.net vb Pin
headshot9x2-Jun-17 22:40
headshot9x2-Jun-17 22:40 
SuggestionDatabase example Pin
headshot9x7-Feb-17 17:21
headshot9x7-Feb-17 17:21 
GeneralMy vote of 4 Pin
Carlos Alberto Morales Osorio15-Nov-15 12:03
professionalCarlos Alberto Morales Osorio15-Nov-15 12:03 
GeneralRe: My vote of 4 Pin
headshot9x2-Jun-17 22:35
headshot9x2-Jun-17 22:35 
QuestionStore Procedure Pin
Hessam Mir Tabatabaee14-Jul-15 0:17
Hessam Mir Tabatabaee14-Jul-15 0:17 
AnswerRe: Store Procedure Pin
headshot9x2-Jun-17 22:35
headshot9x2-Jun-17 22:35 
QuestionUser Identification prior to shopping Pin
Member 112812643-Dec-14 11:13
Member 112812643-Dec-14 11:13 
AnswerRe: User Identification prior to shopping Pin
headshot9x23-Mar-15 0:24
headshot9x23-Mar-15 0:24 
GeneralStore Procedure Please Pin
Jose Alberto Lujan Huachhuaco4-Nov-14 15:10
Jose Alberto Lujan Huachhuaco4-Nov-14 15:10 
GeneralRe: Store Procedure Please Pin
headshot9x2-Jun-17 22:33
headshot9x2-Jun-17 22:33 
GeneralStored Procedures Pin
Member 1065730612-Mar-14 23:02
Member 1065730612-Mar-14 23:02 
GeneralRe: Stored Procedures Pin
headshot9x2-Jun-17 22:33
headshot9x2-Jun-17 22:33 
QuestionC# code Pin
Member 1058794711-Feb-14 1:29
Member 1058794711-Feb-14 1:29 
AnswerRe: C# code Pin
thatraja27-Feb-14 1:29
professionalthatraja27-Feb-14 1:29 
AnswerRe: C# code Pin
ghatiya27-Apr-14 21:05
ghatiya27-Apr-14 21:05 
AnswerRe: C# code Pin
headshot9x2-Jun-17 22:33
headshot9x2-Jun-17 22:33 
QuestionWhat is 'errcode' in the Login.aspx page and where is this found? Pin
Rick Lister11-Feb-13 4:48
Rick Lister11-Feb-13 4:48 
AnswerRe: What is 'errcode' in the Login.aspx page and where is this found? Pin
headshot9x2-Jun-17 22:31
headshot9x2-Jun-17 22:31 
QuestionI m getting some prob Please Help Pin
Shashangka_Shekhar15-Jan-13 8:06
Shashangka_Shekhar15-Jan-13 8:06 
AnswerRe: I m getting some prob Please Help Pin
headshot9x15-Jan-13 14:47
headshot9x15-Jan-13 14:47 
GeneralRe: I m getting some prob Please Help Pin
samflex27-Aug-14 3:39
samflex27-Aug-14 3:39 
GeneralRe: I m getting some prob Please Help Pin
headshot9x2-Jun-17 22:30
headshot9x2-Jun-17 22:30 
GeneralRe: I m getting some prob Please Help Pin
samflex12-Jun-17 11:06
samflex12-Jun-17 11:06 
QuestionRegarding Shopping Cart Pin
Sumit_Kumar_Sinha17-Oct-12 23:33
Sumit_Kumar_Sinha17-Oct-12 23:33 
Hi,
How, is it possible to store shopcart in Profile instead of session.........if possible then pl'z explain with profile.

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

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