Click here to Skip to main content
15,891,848 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.6K   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 
This article discusses how to create an order page and shopping cart page using GridView ASP.NET C# and SQL Server

Create three tables:
Screenshot - P11.gif

Create a web Project
Create an Images Folder in the project solution
Add some image file into the Images folder
Screenshot - P2.gif

Rename the Default.aspx web page to OrderPage.aspx
Drag and drop GridView object from the toolbox on to the web form.
Create the following GridView Columns and set the GridView AutoGenerateColumn to false.
Screenshot - p3.gif

Where AddToCart is a button, Picture ID, Title and Date Added are text fields and PictureURL is Image field.
GridView will look like this:
Screenshot - p4.gif

When the order page is loaded, all the items have to be loaded to the GridView for the user to select, copy the following code to the load page event:
Collapse | Copy Code
string Sel = "Select * from ItemTable";
SqlConnection Con = new SqlConnection(Cn);
SqlCommand cmd = new SqlCommand(Sel, Con);
Con.Open();
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("PictureID", typeof(int)));
dt.Columns.Add(new DataColumn("PictureURL", typeof(string)));
dt.Columns.Add(new DataColumn("Title", typeof(string)));
dt.Columns.Add(new DataColumn("DateAdded", typeof(DateTime)));
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
DataRow dr = dt.NewRow();
dr["PictureID"] = Convert.ToInt32(reader["PictureId"]);
dr["PictureURL"] = ResolveUrl("~/Images/" +reader["PictureURL"]);
dr["Title"] = reader["Title"];
dr["DateAdded"] = reader["DateAdded"];
dt.Rows.Add(dr);
}
Con.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
Where Cn Is the connection string.

Enter some data to the SQL table:
Screenshot - p5.gif

Screenshot - p6.gif

Build and run the application.
The following result will be displayed:
Screenshot - p7.gif

AddToCart button click event:
Screenshot - p8.gif

Set the AddToCart button property.

Add this to the GridView property using the source page or the HTML page
OnRowCommand="GridView1_RowCommand"
Add these lines of code to the page code behind:
Collapse | Copy Code
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AddToCart")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
AddShopCart(row.Cells[1].Text.ToString());
}
}
After you click the AddToCart button, you need to move the item to the shopping cart. To do that, you need to write code to make a data entry to OrderTable, since ItemId is unique. Based on ItemId we insert a data entry to the OrderTable.
Before we make an entry to the table we need order Number, we can get the order number from ControlTable since ControlTable holds the last used order number.
The method to insert selected item to shopping cart will get the last used order number from ControlTable, and after inserting the values to the OrderTable will update the order number in the ControlTable.
Collapse | Copy Code
private void AddShopCart(string ItemId)
{
string ord = OrderNumber();
if (ord != "Bad order")
{
int ordernumber = Convert.ToInt32(ord);
ordernumber += 1;
SqlConnection C_n = new SqlConnection(Cn);
SqlCommand cm = new SqlCommand("Insert INTO OrderTable VALUES
('" + ordernumber + "', '" + ItemId + "', '" + "101" +
"', '" + Convert.ToDateTime("2/19/2007") + "','" + "1" + "')", C_n);
C_n.Open();
SqlDataReader dr = cm.ExecuteReader();
C_n.Close();
UpdateOrderNumber(ordernumber);
}
}
The method to get the last used order number.
Collapse | Copy Code
private string OrderNumber()
{
SqlConnection Or_Cn = new SqlConnection(Cn);
SqlCommand Or_Cm = new SqlCommand("Select OrderNumber from ControlTable", Or_Cn);
Or_Cn.Open();
SqlDataReader Or_rd = Or_Cm.ExecuteReader();
if (Or_rd.Read())
{
return Or_rd["OrderNumber"].ToString();
}
else
{
return "Bad order";
}
}
The method to update the order number in the ControlTable:
Collapse | Copy Code
private void UpdateOrderNumber(int UpdatedNumber)
{
SqlConnection Op_Cn = new SqlConnection(Cn);
SqlCommand Op_Cm = new SqlCommand
("Update ControlTable Set OrderNumber=" + UpdatedNumber, Op_Cn);
Op_Cn.Open();
SqlDataReader Op_rd = Op_Cm.ExecuteReader();
Op_Cn.Close();
}
Add new page to the project and name it ShoppingCart.aspx.
Drag and drop GridView object from the toolbox on to the web form.
Create the following GridView columns and set the GridView AutoGenerateColumn to false.
Screenshot - p9.gif

Where Delete is a button, Picture ID, Title, Price and Date Added are text fields and PictureURL is Image field.
GridView will look like this:
Screenshot - p10.gif

Under page load event, copy the following code:
Collapse | Copy Code
string Sel = "Select a.* from ItemTable as a INNER JOIN
OrderTable as b ON a.PictureId=b.ItemId";
SqlConnection Con = new SqlConnection(Cn);
SqlCommand cmd = new SqlCommand(Sel, Con);
Con.Open();
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("PictureID", typeof(int)));
dt.Columns.Add(new DataColumn("Title", typeof(string)));
dt.Columns.Add(new DataColumn("Price", typeof(string)));
dt.Columns.Add(new DataColumn("DateAdded", typeof(DateTime)));
dt.Columns.Add(new DataColumn("PictureURL", typeof(string)));
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
DataRow dr = dt.NewRow();
dr["PictureID"] = Convert.ToInt32(reader["PictureId"]);
dr["Title"] = reader["Title"];
dr["Price"] = reader["Price"];
dr["DateAdded"] = reader["DateAdded"];
dr["PictureURL"] = ResolveUrl("~/Images/" + reader["PictureURL"]);
dt.Rows.Add(dr);
}
Con.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
Build and run. After placing some order, make the shopping cart startup page and you will see all the orders you have placed listed there.
License
Mahesh Nagarkar

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 

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.