Click here to Skip to main content
15,893,401 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
public partial class AddToCart : System.Web.UI.Page
{
    decimal total;
    DataTable cart = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["currentUId"] == null)
            Response.Redirect("~/Account/Login.aspx");

        if (Session["cart"] != null)
        {
            //Response.Write(cart.Rows[0]["p_id"].ToString());
            ///read cart from session if exist
            cart = (DataTable)Session["cart"];

            //GridView4.DataSource = cart;
            //GridView4.DataBind();

            //total = Convert.ToDecimal(Session["total"].ToString());
        }
        else
        {
            //create an empty DataTable and Add some columns to it
            cart = new DataTable();
            cart.Columns.Add("p_id", typeof(int));
            cart.Columns.Add("p_name", typeof(string));
            cart.Columns.Add("p_price", typeof(decimal));
            cart.Columns.Add("p_quantity", typeof(int));
            cart.Columns.Add("item_total", typeof(decimal));
            //total = 0;

        }
        refreshTotal();

        if (Request["DelID"] != null)
        {
            for (int i = 0; i < cart.Rows.Count; i++)
            {
                if (cart.Rows[i]["p_id"].ToString() == Request["DelID"].ToString())
                    cart.Rows.Remove(cart.Rows[i]);
            }
            Session["cart"] = cart;
            refreshTotal();
        }
        if (Request["ID"] != null)
        {
            //search item in DataTable
            bool Found = false;
            for (int i = 0; i < cart.Rows.Count; i++)
            {
                if (cart.Rows[i]["p_id"].ToString() == Request["ID"].ToString())
                    Found = true;
            }
            //add to basket if not yet added by customer
            if (Found == false)
            {
                int pid = Convert.ToInt16(Request["ID"]);
                DataTable dt = new DataTable();
                using (SqlConnection conn = new SqlConnection(SqlDataSource1.ConnectionString.ToString()))
                {
                    using (SqlCommand comm = new SqlCommand("select ProductName,UnitCost from Products where ProductID = " + pid, conn))
                    {
                        conn.Open();
                        using (SqlDataReader myReader = comm.ExecuteReader())
                        {
                            dt.Load(myReader);
                        }
                        conn.Close();
                    }
                }
                // the sqldatareader reads a single row only since products have a unique p_id
                string name = (string)dt.Rows[0]["ProductName"];
                decimal price = (decimal)dt.Rows[0]["UnitCost"];

                //                Response.Write("Product : " + name + " of price: " + price + "<br/>");
                {
                    cart.Rows.Add(new object[] { Request["ID"], name, price, (int)1, (decimal)price * 1 });
                }
            }
            Session["cart"] = cart;
            refreshTotal();

        }

        if (IsPostBack == false)
        {
            GridView4.DataSource = cart;
            GridView4.DataBind();
            refreshTotal();
        }
        refreshTotal();
    }
    protected void refreshCart()
    {
        for (int i = 0; i < GridView4.Rows.Count; i++)
        {
            TextBox Tb = (TextBox)GridView4.Rows[i].FindControl("TextBoxCount");
            cart.Rows[i]["p_quantity"] = Convert.ToInt16(Tb.Text);
            //Response.Write("quantity : " + Tb.Text + " : ");

            decimal qxp = (decimal)((Convert.ToInt32(Tb.Text) * (decimal)cart.Rows[i]["p_price"]));
            cart.Rows[i]["item_total"] = qxp;
            //Response.Write("  >>  Total" + qxp.ToString() + "<br/>");
        }

        refreshTotal();
        Response.Redirect("~/Products.aspx");
    }
    protected void refreshTotal()
    {
        total = (decimal)0;
        for (int i = 0; i < cart.Rows.Count; i++)
        {
            //Response.Write(total);
            total += (decimal)(cart.Rows[i]["item_total"]);
        }
        Label1.Text = total.ToString();
        Session["total"] = total;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        refreshCart();
        //Response.Write(total.ToString());
        //Response.Write((string)GetMaxRequest().ToString());
    }
    protected int GetMaxRequest()
    {
        using (SqlConnection conn = new SqlConnection(SqlDataSourceRequest.ConnectionString.ToString()))
        {
            SqlCommand maximum = new SqlCommand("SELECT MAX(R_Id) as maximum FROM [Requests]", conn);
            conn.Open();
            int m = Convert.ToInt32(maximum.ExecuteScalar());
            conn.Close();
            return m + 1;
        }
    }
    protected void InsertOrder(int r_id, int p_id, int p_quantity, decimal item_total)
    {

        using (SqlConnection conn = new SqlConnection(SqlDataSourceOrder.ConnectionString.ToString()))
        {
            SqlCommand cmd = new SqlCommand("INSERT INTO [Orders](R_Id, ProductID, quantity,Items_total) VALUES (" + r_id + "," + p_id + "," + p_quantity + "," + item_total + ")", conn);
            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();
        }

    }
    protected void InsertRequest(string UId, string sdate, decimal total)
    {
        using (SqlConnection conn = new SqlConnection(SqlDataSourceRequest.ConnectionString.ToString()))
        {
            SqlCommand cmd = new SqlCommand("INSERT INTO Requests(C_Id, R_Time,R_total) VALUES ('" + UId + "','" + sdate + "'," + total + ")", conn);
            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        int r_id = GetMaxRequest();
        for (int i = 0; i < cart.Rows.Count; i++)
        {
            InsertOrder((int)r_id, Convert.ToInt16(cart.Rows[i]["p_id"]), Convert.ToInt16(cart.Rows[i]["p_quantity"]), Convert.ToDecimal(cart.Rows[i]["item_total"]));
        }
        InsertRequest(Session["currentUId"].ToString(), DateTime.Now.ToString(), (decimal)total);

        //Session["ctrl"] = pnl1;
        ClientScript.RegisterStartupScript(this.GetType(), "onclick", "<script language=javascript>window.open('Print.aspx','PrintMe','height=300px,width=300px,scrollbars=1');</script>");
        //Session["total"] = null;
        Session["cart"] = null;
        Session["r_id"] = r_id;
        Response.Write("<div class=response> Thank You For Purchasing Our Products</div>");
    }
}
Posted
Comments
[no name] 1-May-13 15:08pm    
i want it to take the product id from another page ... where i could add it please help
[no name] 1-May-13 16:05pm    
So use a session variable just like you are already using. And you might want to think about not using string concatenation and using parameterized queries instead to avoid SQL injection attacks.
jkirkerx 1-May-13 16:06pm    
Why didn't you just post the part of the code that makes an attempt to get the product ID from another page?

And what is the other page, is it within the same website?

You probably should pass the productID to this current page using a querystring,

send it not fetch or get it.
[no name] 1-May-13 16:36pm    
i want to send the product id from products page within the same project from a gridview that contain this link in every itemview

Add To Cart

then i want to take this id and add it to the cart table how should i use it ... thanks
jkirkerx 1-May-13 16:42pm    
You make hyperlinks or linkbuttons with the url add2cart?pId=12-4578

Or use the session variable like you have, and get the session variable when loading the next page.

1 solution

in pageload in newpage u have to add like this

if (!IsPostBack)
{

if (Request.QueryString.Count > 0)
{
if (Request.QueryString["x"] != null)
{
strproductID = Request.QueryString["x"].ToString();

}

}
else
{
--do something----
}
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900