Wednesday, 10 April 2013

working Shopping Cart in Asp.net C#


How to do Shopping Cart in Asp.net C#



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.

2 comments:

  1. Owsm sir..............just Owsm...the real Dot Net...

    ReplyDelete
  2. Thanks for the article. However cant see images. Please provide source code for reference.

    ReplyDelete