Monday 8 September 2014

Asphelp: Add To Cart In Asp.net

In this article you will learn how to create add to cart using session. In this program session is used to fill up the detail of user after that user will be able to add the product in cart

Download Source

Create Table Login
CREATE TABLE [dbo].[login](
        [id] [int] IDENTITY(1,1) NOT NULL,
        [username] [varchar](50) NULL,
        [password] [varchar](50) NULL,
        [c_date] [datetime2](7) NULL
) ON [PRIMARY]

Create Table Product
CREATE TABLE [dbo].[product](
        [id] [int] IDENTITY(1,1) NOT NULL,
        [name] [varchar](50) NULL,
        [amount] [varchar](50) NULL,
        [qty] [varchar](50) NULL,
        [imagepath] [varchar](max) NULL,
        [c_date] [datetime2](7) NULL
) ON [PRIMARY]

Create Table Cart
CREATE TABLE [dbo].[cart](
        [id] [int] IDENTITY(1,1) NOT NULL,
        [pro_id] [varchar](50) NULL,
        [pro_name] [varchar](50) NULL,
        [pro_amount] [varchar](50) NULL,
        [qty] [int] NULL,
        [pro_image] [varchar](50) NULL,
        [subtotal] [int] NULL,
        [total] [int] NULL,
        [uname] [varchar](50) NULL
) ON [PRIMARY]

HTML CODE
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="assets/css/styles.css" rel="stylesheet" />
    <link href="assets/css/button.css" rel="stylesheet" />
    <script src="Popup/popup.js"></script>
    <link href="Popup/style.css" rel="stylesheet" />
    <link href="assets/css/txtbox.css" rel="stylesheet" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <style>
        #tbl1 {
            border: groove 2px;
            border-radius: 13px 13px 13px 13px;
            padding: 10px;
            margin: 5px;
            min-height: 300px;
            min-width: 230px;
            box-shadow: 3px 5px 15px #b6b6b6;
        }

            #tbl1 img {
                height: 150px;
                width: 150px;
                transition-duration: 1.2s;
            }

                #tbl1 img:hover {
                    position: absolute;
                    transition-duration: 0.2s;
                    min-height: 200px;
                    min-width: 200px;
                    margin-top: -120px;
                    margin-left: -10px;
                    z-index: 999;
                }

        #output {
            float: right;
            border: groove;
            width: 315px;
            margin: 11px;
            box-shadow: 3px 5px 15px #b6b6b6;
            border-radius: 13px 13px 13px 13px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <asp:UpdatePanel runat="server">
            <ContentTemplate>
                <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
                <div>
                    <table style="float: right">
                        <tr>
                            <td>
                                <b>
                                    <asp:Label ID="lbluname" runat="server"></asp:Label></b></td>
                            <td><a onclick="openOffersDialog();" class="shiny-button" id="login" runat="server">Login/Create</a>
                                <input type="submit" class="shiny-button" onserverclick="btnlogout_ServerClick" value="Logout" visible="false" id="btnlogout" runat="server" />
                            </td>
                        </tr>
                    </table>
                    <table>
                        <tr>
                            <td>
                                <img id="img2" runat="server" width="300" src="~/image/shoplogo.png" /></td>
                            <td>
                                <nav>
                                    <ul class="fancyNav">
                                        <li id="home"><a href="#home" class="homeIcon">Home</a></li>
                                        <li id="news"><a href="#Product">Product</a></li>
                                        <li id="about"><a href="#about">About us</a></li>
                                        <li id="services"><a href="#services">Services</a></li>
                                        <li id="Li1"><a href="#services">Contact</a></li>
                                    </ul>
                                </nav>
                            </td>
                        </tr>
                    </table>
                </div>
            </ContentTemplate>
        </asp:UpdatePanel>
        <div style="float: left">
            <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <ContentTemplate>
                    <asp:DataList ID="datalist1" runat="server" RepeatDirection="Horizontal" RepeatColumns="4" OnItemCommand="datalist1_ItemCommand">
                        <ItemTemplate>
                            <table id="tbl1">
                                <tr style="height: 10%;">
                                    <td style="text-align: center;" colspan="2"><b>
                                        <asp:Label ID="lblname" Font-Size="22px" runat="server" Text='<%#Eval("name") %>'></asp:Label></b><hr />
                                    </td>
                                </tr>
                                <tr>
                                    <td colspan="2" style="height: 80%;">
                                        <img id="img1" class="img1" runat="server" src='<%#Eval("imagepath") %>' /></td>
                                    <td></td>
                                </tr>
                                <tr style="height: 10%;">
                                    <td>Rs:<asp:Label ID="lblprice" runat="server" Text='<%#Eval("amount") %>'></asp:Label></td>
                                    <td>
                                        <input type="hidden" id="hiddenid" value='<%# DataBinder.Eval(Container.DataItem, "id") %>' runat="server" />
                                        <input type="hidden" id="hiddenname" value='<%# DataBinder.Eval(Container.DataItem, "name") %>' runat="server" />
                                        <input type="hidden" id="hiddenamount" value='<%# DataBinder.Eval(Container.DataItem, "amount") %>' runat="server" />
                                        <input type="hidden" id="hiddenimg" value='<%# DataBinder.Eval(Container.DataItem, "imagepath") %>' runat="server" />
                                        <asp:Button ID="btnwishlist" runat="server" Text="Add To cart" CommandName="Add" CssClass="shiny-button" /></td>
                                </tr>
                            </table>
                        </ItemTemplate>
                    </asp:DataList>
                </ContentTemplate>
            </asp:UpdatePanel>
        </div>
        <div id="output">
            <asp:UpdatePanel runat="server">
                <ContentTemplate>
                    <table>
                        <tr>
                            <td>
                                <img src="image/cart.png" width="45" height="45" /></td>
                            <td>
                                <asp:Label ID="lblcount" runat="server" Font-Size="X-Large"></asp:Label></td>
                        </tr>
                    </table>
                </ContentTemplate>
            </asp:UpdatePanel>
            <hr />
            <div style="border-bottom: groove 1px; min-height: 220px;">
                <asp:UpdatePanel runat="server">
                    <ContentTemplate>
                        <asp:Repeater ID="rptcart" runat="server" OnItemCommand="rptcart_ItemCommand">
                            <ItemTemplate>
                                <table style="width: 100%">
                                    <tr>
                                        <td style="width: 30%">
                                            <img id="img1" class="img1" runat="server" width="40" height="40" src='<%#Eval("pro_image") %>' /></td>
                                        <td style="width: 30%">
                                            <asp:Label ID="lblqty" runat="server" Text='<%#Eval("qty") %>'></asp:Label></td>
                                        <td style="width: 30%">
                                            <asp:Label ID="lblprice" runat="server" Text='<%#Eval("pro_amount") %>'></asp:Label></td>
                                        <td style="width: 10%">
                                            <asp:ImageButton CommandName="delete" ID="btndelete" runat="server" ImageUrl="~/image/close.png" CommandArgument='<%#Eval("pro_id") %>' Width="15" Height="15" /></td>
                                    </tr>
                                </table>
                            </ItemTemplate>
                        </asp:Repeater>
                    </ContentTemplate>
                </asp:UpdatePanel>
            </div>
            <div style="height: 125px;">
                <asp:UpdatePanel runat="server">
                    <ContentTemplate>
                        <table width="98%">
                            <tr>
                                <td style="text-align: center; width: 50%">
                                    <br />
                                    <b style="font-size:15px">Your Total : </b>
                                    <b><asp:Label ID="lbltotalamt" runat="server" Font-Size="15px"></asp:Label></b></td>
                            </tr>
                            <tr>
                                <td style="text-align: center; width: 50%;">
                                    <br />
                                    <input type="submit" id="btnempty" runat="server" style="font-size: 15px" value="Clear Cart" class="shiny-button" /></td>
                                <td style="text-align: center; width: 50%">
                                    <br />
                                    <input type="submit" id="btnproceed" runat="server" style="font-size: 15px" value="Place Order" class="shiny-button" /></td>
                            </tr>
                        </table>
                    </ContentTemplate>
                </asp:UpdatePanel>
            </div>
        </div>
        <asp:UpdatePanel runat="server">
            <ContentTemplate>
                <div id="wrapper">
                    <div id="overlay" class="overlay"></div>
                    <div id="boxpopup" class="box">
                        <a onclick="closeOffersDialog('boxpopup');" class="boxclose"></a>
                        <h3>Login Form</h3>
                        <hr />
                        <label>
                            <b>Username: </b>
                        </label>
                        <br />
                        <input type="text" id="txtuname" placeholder="Name" runat="server" /><br />
                        <br />
                        <label>
                            <b>Password: </b>
                        </label>
                        <br />
                        <input type="password" id="txtpassword" placeholder="Password"  runat="server" /><br />
                        <br />
                        <input style="margin-left:80px;" id="btnlogin" value="Login" onserverclick="btnlogin_ServerClick" class="shiny-button" runat="server" type="submit" />
                        <input type="submit" id="btncreate" runat="server" class="shiny-button" value="Create" onserverclick="btncreate_ServerClick"  />                       
                        <br />
                    </div>
                </div>
            </ContentTemplate>
        </asp:UpdatePanel>
    </form>
</body>
</html>

C# CODE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

namespace AddToCart
{
    public partial class Home_page : System.Web.UI.Page
    {        
        string conn = "Data Source=Servername;Initial Catalog=DatabaseName;Integrated Security=True";
        public static string value;
        static DataSet ds = new DataSet();
        public static DataTable cartdata = new DataTable();
        public static string total;

        protected void Page_Load(object sender, EventArgs e)
        {            
            BindDataRecord();
        }

        public void BindDataRecord()
        {
            SqlConnection con = new SqlConnection(conn);
            con.Open();
            try
            {
                if (!Page.IsPostBack)
                {                   
                    SqlCommand cmd = new SqlCommand("Select * From product", con);
                    SqlDataAdapter ad = new SqlDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    ad.Fill(ds);
                    datalist1.DataSource = ds.Tables[0];
                    datalist1.DataBind();
                }
            }
            catch (Exception ex)
            {

            }
            finally
            {
                con.Close();
            }
        }

        public void BindCartData()
        {
            SqlConnection con = new SqlConnection(conn);
            try
            {               
                con.Open();
                SqlCommand cmd = new SqlCommand("select * from cart where uname='" + Session["username"].ToString() + "'", con);
                SqlDataAdapter ad = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                ad.Fill(ds);
                cartdata = ds.Tables[0];
                rptcart.DataSource = ds.Tables[0];
                rptcart.DataBind();
                CountTotalAmount();
                CountCartItems();
                con.Close();              
            }
            catch (Exception ex)
            {

            }
            finally
            {
                con.Close();
            }
        }

        protected void datalist1_ItemCommand(object source, DataListCommandEventArgs e)
        {
            SqlConnection con = new SqlConnection(conn);
            con.Open();
            try
            {
                if (Session["username"] != null)
                {
                    if (e.CommandName == "Add")
                    {
                        string id = ((HtmlInputHidden)e.Item.FindControl("hiddenid")).Value;
                        string name = ((HtmlInputHidden)e.Item.FindControl("hiddenname")).Value;
                        string amount = ((HtmlInputHidden)e.Item.FindControl("hiddenamount")).Value;
                        string image = ((HtmlInputHidden)e.Item.FindControl("hiddenimg")).Value;
                        string username = HttpContext.Current.Session["username"].ToString();
                        Session["Pro_id"] = id;
                        SqlCommand cmd = new SqlCommand("select * from cart where uname='" + Session["username"].ToString() + "' And pro_id='" + id + "'", con);
                        SqlDataAdapter ad = new SqlDataAdapter(cmd);
                        DataSet ds = new DataSet();
                        ad.Fill(ds);
                        if (ds.Tables[0].Rows.Count > 0)
                        {

                        }
                        else
                        {
                            SqlCommand cmd2 = new SqlCommand("Insert into cart(pro_id,pro_name,pro_amount,pro_image,subtotal,total,uname) values('" + id + "','" + name + "','" + amount + "','" + image + "','" + amount + "','" + amount + "','" + username + "')", con);
                            cmd2.ExecuteNonQuery();
                            cmd2.Dispose();                          
                            BindCartData();                            
                        }
                    }
                }
                else
                {
                    ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Please Login')</script>");
                }
            }
            catch (Exception ex)
            {

            }
            finally
            {
                con.Close();
            }
        }

        protected void btnlogin_ServerClick(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(conn);
            con.Open();
            try
            {
                SqlCommand cmd = new SqlCommand("Select * from login where username=@username and password=@password", con);
                cmd.Parameters.AddWithValue("@username", txtuname.Value);
                cmd.Parameters.AddWithValue("@password", txtpassword.Value);
                SqlDataAdapter ad = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                ad.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    Session["username"] = txtuname.Value;
                    lbluname.Visible = true;
                    lbluname.Text = "Welcome " + Convert.ToString(Session["username"]);
                    btnlogout.Visible = true;
                    login.Visible = false; 
                    BindCartData();                   
                }
                else
                {
                    lbluname.Visible = false;
                    btnlogout.Visible = false;
                    login.Visible = true;
                    ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");
                }
            }
            catch (Exception ex)
            {

            }
            finally
            {
                con.Close();
            }
        }

        public void CountTotalAmount()
        {
            SqlConnection con = new SqlConnection(conn);
            con.Open();
            SqlCommand cmd5 = new SqlCommand("select sum(subtotal) from cart where uname='" + Session["username"].ToString() + "'", con);           
            lbltotalamt.Text = cmd5.ExecuteScalar().ToString();           
            con.Close();
        }

        public void CountCartItems()
        {
            SqlConnection con = new SqlConnection(conn);
            con.Open();
            SqlCommand cmd3 = new SqlCommand("select COUNT(pro_id) from cart where uname='" + Session["username"].ToString() + "'", con);           
            lblcount.Text = cmd3.ExecuteScalar().ToString();
            con.Close();
            CountTotalAmount();
        }

        protected void btnlogout_ServerClick(object sender, EventArgs e)
        {
            Session.Clear();
            Session.RemoveAll();
            Session.Abandon();
            Response.Redirect(Request.RawUrl);
        }

        protected void rptcart_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            SqlConnection con = new SqlConnection(conn);
            if (e.CommandName == "delete")
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("delete from cart where pro_id=@id", con);
                cmd.Parameters.AddWithValue("@id", e.CommandArgument);
                cmd.ExecuteNonQuery();
                cmd.Dispose();               
                con.Close();               
                BindCartData();
            }
        }

        protected void btncreate_ServerClick(object sender, EventArgs e)
        {
            if (Session["username"] !=null)
            {
               
            }
            else
            {
                SqlConnection con = new SqlConnection(conn);
                con.Open();
                SqlCommand cmd = new SqlCommand("insert into login(username,password) values('" + txtuname.Value + "','" + txtpassword.Value + "')", con);
                cmd.ExecuteNonQuery();
                Session["username"] = txtuname.Value;
                lbluname.Text = "Welcome " + Convert.ToString(Session["username"]);
                con.Close();
                lbluname.Visible = true;
                btnlogout.Visible = true;
                login.Visible = false;
                BindCartData();
            }
        }
    }
}

Output Preview

add to cart | dotnetasphelp


Download Source