How to use Asp.net
  • Home
  • About us
  • Disclaimer
  • joy of helping
KEEP IN TOUCH

How to do Shopping Cart in Asp.net C#

Oct07
2011
8 Comments Written by vikram

Hello there, I am just trying to do Shopping Cart simple way. Hope it will help you. To create a shopping cart we almost used the Product Details like Quantity, Price, Code etc. and we can add it more columns according to requirement. Well in this article I m using only two pages name Products.aspx and shopping_cart.aspx from Products page I will send the id of product code to shopping cart page and fill the Gridview with the product detail after getting the id from Query string. Well copy the following Database Script.
*you can use product title and description as well in database.

DATABASE SCRIPT

DATABASE SCRIPT
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N’[dbo].[tbl_Product]‘) AND type in (N’U'))
BEGIN
CREATE TABLE [dbo].[tbl_Product](
[id] [bigint] IDENTITY(1,1) NOT NULL,
[Image] [nvarchar](200) NULL,
[Title] [nvarchar](50) NULL,
[description] [nvarchar](max) NULL,
[our_price] [bigint] NULL,
[size] [nvarchar](20) NULL,
[Product_quantity] [bigint] NULL CONSTRAINT [DF_tbl_Product_Product_quantity]  DEFAULT ((0)),
[Product_code] [nvarchar](20) NULL,
[date] [datetime] NULL CONSTRAINT [DF_tbl_Product_date]  DEFAULT (getdate()),
CONSTRAINT [PK_tbl_Product] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END

 

In your Website Add two pages and name it.
(i) Products.aspx
(ii) Shopping_Cart.aspx
Add DATALIST control on Products.aspx page,
(to learn how to bind DATALIST refer this link:-  http://howtouseasp.net/datalist-paging-with-editing-deleting-and-updating-with-ado-net-way-c/
Add GRIDVIEW  control on Shopping_Cart.aspx,
(to learn how to bind GRIDVIEW refer this link:-  http://howtouseasp.net/how-to-use-gridview-with-insert-edit-update-delete-the-ado-net-way-c/


Following the source code of Products.aspx page

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Products.aspx.cs” Inherits=”Products” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title>Untitled Page</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:DataList ID=”DataList1″ runat=”server”   RepeatColumns=”3″  DataKeyField=”id”
CellPadding=”15″ Width=”508px”>
<ItemTemplate>
<a href=’Shopping_Cart.aspx?cart_id=<%# Eval(“id”) %>’>
<img alt=”"  src=’Admin/prd_images/<%#Eval(“Image”) %>’ /><br />
</a>
<h4><asp:Label ID=”lb” runat=”server” Font-Bold=”True” Font-Size=”12pt” Text=’<%# Eval(“Title”) %>’></asp:Label><br />
Product Code: <span><%# Eval(“product_code”) %></span></h4>
<span ><del>&#2352;</del><%# Eval(“Our_price”) %> INR</span><br />
<a href=’Shopping_Cart.aspx?cart_id=<%# Eval(“id”) %>’>Add to Cart</a>

</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
</html>


CODING

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class Products : System.Web.UI.Page
{
SqlConnection con = new SqlConnection();
SqlDataAdapter adp = new SqlDataAdapter();
SqlCommand cmd;
DataTable tb;

DataTable dt = new DataTable();

//string a, b;
//string a, save, fn, b, aguid,fn1,aguid1,save1;
private PagedDataSource pagedData = new PagedDataSource();
decimal last1;
Int32 count, no;

protected void Page_Load(object sender, EventArgs e)
{

con.ConnectionString = ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
try
{
con.Open();
//TeSection_txt.Text = Request.QueryString["a"].ToString();

if (Page.IsPostBack == false)
{
try
{

doPaging();

}
catch
{

}
}
}
catch
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
}
con.Close();

}

//fetching the records

public DataTable getTheData()
{

dt = new DataTable();
adp = new SqlDataAdapter(“select * from tbl_Product”, con);

adp.Fill(dt);
adp.Dispose();
DataList1.DataSource = dt;
DataList1.DataBind();
if (dt.Rows.Count == 0)
{
//lbl_msg.Text = “Gallery is empty “;
}
else
{
Session["cnt"] = Convert.ToInt32((dt.Rows.Count));

}
return dt;
}

private void doPaging()
{
//calling the getTheData() and fillin into pagedDataSource.
pagedData.DataSource = getTheData().DefaultView;
pagedData.AllowPaging = true;
pagedData.PageSize = 3;
count = Convert.ToInt32(Session["cnt"]);
last1 = count / pagedData.PageSize;   //total record
if (count % pagedData.PageSize == 0)
{
last1 = –last1;

}
last1 = Math.Ceiling(last1);
// Last record this is becaz if u have 3 record and displayin 2 in one page the 3rd on will display on another page….
try
{
pagedData.CurrentPageIndex = Int32.Parse(Request["Page"].ToString());

}
catch
{
pagedData.CurrentPageIndex = 0;
}
//for paging u can use following code.

//Prv_btn.Visible = (!pagedData.IsFirstPage);
//first_btn.Visible = (!pagedData.IsFirstPage);
//Next_btn.Visible = (!pagedData.IsLastPage);
//Last_btn.Visible = (!pagedData.IsLastPage);

DataList1.DataSource = pagedData;
DataList1.DataBind();
}

}

 

 

Following the source code of Shopping_Cart.aspx  page

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Shopping_Cart.aspx.cs” Inherits=”Shopping_Cart” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title>Untitled Page</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<br />
<asp:LinkButton ID=”LinkButton1″ runat=”server” PostBackUrl=”~/Products.aspx”>Continue Shopping</asp:LinkButton>
<br />
<br />
<br />

<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False”
onrowdeleting=”GridView1_RowDeleting” onrowcommand=”GridView1_RowCommand”
ShowFooter=”True”>
<Columns>

<asp:TemplateField HeaderText=”Details”>
<ItemTemplate>
<span><%# Eval(“title”) %></span> (<span><%# Eval(“product_code”) %></span>) <br />

</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText=”Item Price”>
<ItemTemplate>
<del>र</del> <%# Eval(“our_price”) %>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText=”Quantity”>
<ItemTemplate>
<asp:TextBox ID=”txt_qty” runat=”server”></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
Total:
</FooterTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText=”Total” >
<FooterTemplate>
<asp:Label ID=”lbl_total” runat=”server” Font-Bold=”True”></asp:Label>
</FooterTemplate>
<ItemTemplate>
<del>र</del> <%# Eval(“Total”) %>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField>
<FooterTemplate>
<asp:LinkButton ID=”LinkButton2″ runat=”server” CommandName=”abc”>Update</asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
<asp:ImageButton ID=”ImageButton1″ runat=”server” CommandName=”delete” style=”text-align:right”
ImageUrl=”~/images/icon_delete.png”  Height=”24px” Width=”24px”/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle HorizontalAlign=”Left” />

</asp:GridView>
<asp:Label ID=”lbl_total” runat=”server” ForeColor=”#CC0000″></asp:Label>
</div>
</form>
</body>
</html>

 


CODING

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class Shopping_Cart : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(); // for connection
SqlDataAdapter adp = new SqlDataAdapter();  // for fetch the records acc. to condition
DataTable dt = new DataTable(); // fill the fetched records
DataTable tb; // will store the session
TextBox txt_qty; // for Product Quantity
Label lb_Footer_total = null; // for total Product Price
DataRowView r; // for Datarows

protected void Page_Load(object sender, EventArgs e)
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
try
{
con.Open();
}
catch
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
}
finally
{
con.Close();
}

try
{
if (Session["ss"] != null) // first attempt to check whether the session is null or not
{
}
else
{
//will create a temporary datatable for shopping cart
//*NOTE column name must be same as in database table
DataTable shop = new DataTable(“Table”); // create a dataTable name shop ["Table"] always be same.

// declare the columns name according to your need.
shop.Columns.Add(new DataColumn(“id”, Type.GetType(“System.Int32″)));
shop.Columns.Add(new DataColumn(“title”, Type.GetType(“System.String”)));
shop.Columns.Add(new DataColumn(“product_code”, Type.GetType(“System.String”)));
shop.Columns.Add(new DataColumn(“our_price”, Type.GetType(“System.Int32″)));
shop.Columns.Add(new DataColumn(“quantity”, Type.GetType(“System.Int32″)));
shop.Columns.Add(new DataColumn(“total”, Type.GetType(“System.Decimal”)));
shop.Columns["total"].Expression = “our_price*quantity”;

Session["ss"] = shop;  // storing in sessi on

}
}

catch (Exception ex)
{
}

if (!IsPostBack)
{
try
{
adp = new SqlDataAdapter(“select * from tbl_Product where id=@id”, con); // will fetch the record acc. to product id
adp.SelectCommand.Parameters.AddWithValue(“@id”, Convert.ToInt32(Request.QueryString["cart_id"])); // query string of product id.
dt = new DataTable();
adp.Fill(dt);
adp.Dispose();

r = dt.DefaultView[0]; // creating DataRow
tb = (DataTable)(Session["ss"]);

// ***************** will append the same id with Quantity. it will not insert if the same product id request  *************************//
Int32 a = tb.Rows.Count; int i;
for (i = 0; i <= a – 1; i += 1)
{
Int32 t = Convert.ToInt32(tb.Rows[i][0]);
if (t == Convert.ToInt32(Request.QueryString["cart_id"]))
{
int k = 1;//Convert.ToInt32(Session["quantity"]);
int k1 = Convert.ToInt32(tb.Rows[i][4]); // column no. of datatable for Qty.
k1 = k1 + k;  // adding qty.
tb.Rows[i][4] = k1; // adding with previous value.

GridView1.DataSource = tb; // displaying the records in Gridview
GridView1.DataBind();

lb_Footer_total = (Label)(GridView1.FooterRow.FindControl(“lbl_total”)); //*** binding footer control with total.
lb_Footer_total.Text = tb.Compute(“sum(total)”, “”).ToString();
grdview(); // refreshing the data in gridview
return;
}
}

}
catch
{ }

DataRow r1; // declaring for Rows

r1 = tb.NewRow(); // assigning and creating the  New Row

r1[0] = Convert.ToInt32(r["id"]); // database columns name after fetching the records acc. to Product ID.
r1[1] = r["title"].ToString();
r1[2] = r["product_code"].ToString();
r1[3] = Convert.ToInt32(r["our_price"]);
//r1[4] = Session["color"]; // here you can use your column name using session. coming from product page
r1[4] = 1; //default will be one

tb.Rows.Add(r1); // Adding the rows

GridView1.DataSource = tb; // displaying the records in Gridview
GridView1.DataBind();

for (int k = 0; k <= tb.Rows.Count – 1; k++)
{
txt_qty = (TextBox)(GridView1.Rows[k].FindControl(“txt_qty”)); // finding textbox for binding in G.View
txt_qty.Text = (tb.Rows[k][4].ToString()); //*** this the 6th column of Temp. table for manipulating the Quantity of products ***//
}

dt.Dispose();

lb_Footer_total = (Label)(GridView1.FooterRow.FindControl(“lbl_total”)); //*** binding footer control with total.
lb_Footer_total.Text = tb.Compute(“sum(total)”, “”).ToString();

// Optional label out side the gridview.
// lbl_total.Text = tb.Compute(“sum(total)”, “”).ToString(); // computing the total of all products

}
}

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
tb = (DataTable)Session["ss"];
tb.Rows.RemoveAt(e.RowIndex); // deleting the current record in Temporary table
grdview();
}
catch
{ }
}

private void grdview()
{
tb = (DataTable)Session["ss"];
if (tb.Rows.Count == 0) // if no record found
{
lbl_total.Text = “Your Shopping Cart is Empty”;

GridView1.DataSource = tb;
GridView1.DataBind();
}
else
{
GridView1.DataSource = tb;
GridView1.DataBind();

for (int k = 0; k <= tb.Rows.Count – 1; k++)
{
txt_qty = (TextBox)(GridView1.Rows[k].FindControl(“txt_qty”)); // finding drodown for binding in G.View
// you can use any control i have used TEXTBOX for Qty u can use DropDownlist etc.
txt_qty.Text = (tb.Rows[k][4].ToString()); //*** this the 6th column of Temp. table for manipulating the Quantity of products ***//

}

lb_Footer_total = (Label)(GridView1.FooterRow.FindControl(“lbl_total”)); //*** binding footer control with total.
lb_Footer_total.Text = tb.Compute(“sum(total)”, “”).ToString();

}
}

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == “abc”) // I have used GridView Rowcommand to UPDATE the Product from shopping cart.
{
tb = (DataTable)Session["ss"];
for (int i = 0; i <= tb.Rows.Count – 1; i++)
{
txt_qty = (TextBox)(GridView1.Rows[i].FindControl(“txt_qty”));
tb.Rows[i][4] = txt_qty.Text; //*** this the 6th column of Temp. table for manipulating the Quantity of products ***//
}
grdview();
}
}

}

 

 

Following the OUTPUT

 

Adding the Product after sending the Cart id of products.

with regards,
vik

 

Posted in Asp.net
SHARE THIS Twitter Facebook Delicious StumbleUpon E-mail
« Alpha Numeric Digit Numbers for password asp.net
» How can create Google Visualization: Geomap in asp.net

8 comments on “How to do Shopping Cart in Asp.net C#”

  1. Abelardo Canche on December 7, 2011 at 6:07 pm said:

    Hola buenas tardes:
    Gracias por tu aportacion me ha ayudado bastante al respecto… Gracias y Saludos Cordiales desde Cancun QRoo..
    in English

    Hey good afternoon:
    Thanks for your input has helped me a lot about it … Thanks and Best Regards from Cancun Quintana Roo ..

    Reply ↓
  2. hemali sachdev on February 4, 2012 at 5:08 am said:

    Hey its nice code. Thanx it helped me, bt further have query that if i want 2 store this product value through session in another table then how to do??? Pls help me if u can.

    Reply ↓
    • admin on February 18, 2012 at 5:41 am said:

      *put the below code where u need.

      DataTable tb_data = new DataTable();
      tb_data = Session(“temptable”); // here u can store ur all records from session to data table.
      savedataintotable();

      private void savedataintotable()
      {
      SqlDataAdapter adp1 = new SqlDataAdapter(“select * from tempregister”, con);
      SqlCommandBuilder cb = new SqlCommandBuilder(adp1);
      DataSet ds1 = new DataSet();
      adp1.Fill(ds1);

      try {
      adp1.Update(tb_data);
      } catch (Exception ex) {

      }
      try
      {
      tb_data.AcceptChanges()
      }
      catch (Exception ex) {
      }
      }

      hope it will help u
      with regards
      vik

      Reply ↓
  3. Minakshi on March 19, 2012 at 5:36 am said:

    Nice article and useful also……!

    Reply ↓
  4. neha on April 27, 2012 at 8:06 pm said:

    nice one but wat will code look like if we use Microsoft Access instead of Sql

    Reply ↓
  5. Shahab on May 18, 2012 at 12:37 pm said:

    Thanks for this Post. I helps me very nice.

    Reply ↓
  6. swati on July 11, 2012 at 9:12 am said:

    its nice code ..bt when i m clicking on Add to Cart button..its not working…pls help me..

    Reply ↓
  7. AnhVu on July 30, 2012 at 10:57 am said:

    Excuse… Thanks for your coding, I tried it but i got wrong at Shopping_Cart.aspx.

    Object reference not set to an instance of an object.
    Line 114:DataRow r1; // declaring for Rows
    Line 115:
    Line 116:r1 = tb.NewRow(); // assigning and creating the New Row
    Line 117:
    Line 118:r1[0] = Convert.ToInt32(r["Id"]); // database columns name after fetching the records acc. to Product ID.
    Please help me, im a complete rookie. Thank in adv!

    Reply ↓

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

*

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Joy of Helping

Any sort of help to the children who are fatherless, poor & are from far-off areas.
Joy of Helping

Facebook Link

Asp dot Net ,Ajax,Xml.

Recent Posts

  • ROW_NUMBER(), NTILE(), partition by, Duplicate Records, CTE sql server 2008
  • How to get second highest Salary sql server 2008
  • Insert values, insert into, insert default value, insert execute and select into sql server 2008
  • How to Bind GridView with SqlDataReader in Asp.net
  • how to attach files to email without storing on disk using Asp.net FileUpload control

Recent Comments

  • Anonymous on ROW_NUMBER(), NTILE(), partition by, Duplicate Records, CTE sql server 2008
  • dhananjay on How to use GridView with Insert, Edit, Update, Delete the Ado.net way C#
  • dev on How can we limit the characters in multiline textbox asp.net using JavaScript
  • navneet on How to display image in Image control after upload on the server asp.net C#
  • AnhVu on How to do Shopping Cart in Asp.net C#

Archives

  • February 2013
  • September 2012
  • April 2012
  • January 2012
  • October 2011
  • August 2011
  • May 2011
  • April 2011
  • March 2011

Categories

  • Asp.net
  • jQuery
  • Sql Server

Meta

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org

EvoLve theme by Theme4Press  •  Powered by WordPress How to use Asp.net