Thursday, 17 May 2012

Shopping Cart in Asp.net

                                               Shopping Cart in asp.net  


create database script 



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]



now
add some dummy data like this

INSERT INTO [tbl_Product] VALUES('pics/Water lilies.jpg','water','water me',23,8,9,'abo3',getdate())

create two pages named
   1. products.aspx
   2.shoppingcart.aspx


html coding of        product pages


<%@ 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">

<script runat="server">

</script>

<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") %>'>
<asp:Image ID="img" runat="server" ImageUrl='<%#Eval("Image") %>' Width="50px" />

</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>


product.aspx  codebehind 



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=new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].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();
}

}

 design looks like -



hill
Product Code: abo1



234 INR
Add to Cart

sun
Product Code: abo2



123 INR
Add to Cart

water
Product Code: abo3



23 INR
Add to Cart

now create, shoppingcart.aspx

html-

<%@ 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>

codebehind of shoppingcart.aspx.cs-

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 = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].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", typeof(Int32)));
shop.Columns.Add(new DataColumn("title",typeof(string)));
shop.Columns.Add(new DataColumn("product_code", typeof(string)));
shop.Columns.Add(new DataColumn("our_price", typeof(Int32)));
shop.Columns.Add(new DataColumn("quantity", typeof(Int32)));
shop.Columns.Add(new DataColumn("total", typeof(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();
}
}

}
design looks like this:

Continue Shopping 


DetailsItem PriceQuantityTotal
hill (abo1) 

 234


 702
 for cancel of product
sun (abo2) 

 123


 123
 for cancel of product
water (abo3) 

 23


 115
 for cancel of product
Total:940Update






No comments:

Post a Comment