Click here to Skip to main content
15,883,819 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
Hello everybody, I am making on a small shopping website project using layer architecture in c# asp.net and now I am working on the cart_page to add the products in the cart_page.Here's below is the code & I use to add the products but it can't works well and products can't be add in the session.So please help me


public partial class Default2 : System.Web.UI.Page
{
    DataTable Basket_DataTable = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["basket"] != null)
        {
            Basket_DataTable = (DataTable)Session["basket"];
        }
        else
        {
            Basket_DataTable = new DataTable();
            Basket_DataTable.Columns.Add("Id");
            Basket_DataTable.Columns.Add("Name");
            Basket_DataTable.Columns.Add("ImageUrl");
            Basket_DataTable.Columns.Add("Price");
            Basket_DataTable.Columns.Add("Item");
            //Basket_DataTable.Columns.Add("total");
        }

        if (Request["DelId"] != null)
        {
            for (int i = 0; i < Basket_DataTable.Rows.Count; i++)
            {
                if (Basket_DataTable.Rows[i][0].ToString() == Request["DelId"].ToString())
                    Basket_DataTable.Rows.Remove(Basket_DataTable.Rows[i]);
            }
        }
        if (Request["Id"] != null)
        {
            bool Found = false;
            for (int i = 0; i < Basket_DataTable.Rows.Count; i++)
            {
                if (Basket_DataTable.Rows[i][0].ToString() == Request["Id"].ToString())
                    Found = true;

            }
            if (Found == false)
            {
                DataAccess.TestDA data = new DataAccess.TestDA();
                string sql = "Select * from Products where Id=" + Request["Id"];
                DataTable ret = data.exe_select(sql);
                if (ret != null && ret.Rows.Count == 1)
                {
                    Basket_DataTable.Rows.Add(new object[]{Request["Id"],ret.Rows[0]["Name"].ToString(),
                      ret.Rows[0]["Price"].ToString(),ret.Rows[0]["ImageUrl"].ToString()
                      ,"1",ret.Rows[0]["Price"].ToString()});


                }

            }
        }
        if (IsPostBack == false)
        {`enter code here`enter code here`
            //GridView2.DataSource = Basket_DataTable;
            GridView2.DataBind();
        }

        Session["basket"] = Basket_DataTable;
    }
Posted
Comments
Sinisa Hajnal 7-Oct-14 4:45am    
"Can't be added" why? What error do you get?

You're adding it here:
Session["basket"] = Basket_DataTable;
Sinisa Hajnal 7-Oct-14 4:47am    
Code comment:
for (int i = 0; i < Basket_DataTable.Rows.Count; i++)
{
if (Basket_DataTable.Rows[i][0].ToString() == Request["Id"].ToString())
Found = true;

}

You should exit the loop once you find the item, no need to loop all the way through.

You'd be better off by using single dataTable.Select("id=' + request["id"] + "'"); statement. No loop needed.
AnoopGharu 7-Oct-14 5:08am    
you are right sir, I already demanding for the "Id" in the below "if(Found==false)" condition, but when I run the project in the browser then it will override the previous product and when I again trying to bring the another product.But if you have better trick rather than this one then please tell because I am new to C# asp.net.Please help me.
Sinisa Hajnal 7-Oct-14 5:53am    
I would if I understood what the problem is. You handle adding products into your table, you're adding the table into the session...what is the problem?

If you run the project, your session starts. If you stop it, your session stops too and the next time your get new session (and empty table). You have to keep the session to add more then one product into it. Just the way user would buy more then one product in one session.

Each time you restart, you're doing it as new user.

In the solution there your code above, changed the way I would write it - in general, I would write separate methods for data retrieval and datatable creation etc...but keeping everything in your load it looks like that. :)
AnoopGharu 7-Oct-14 6:05am    
I want to add more products into the cart_page, but it can add only one product at a time while I run the project into the browser,if I trying to add another product then it can be override the previous one which is already there.This is main problem and what's the reason,why it can be unable to keep store the more than one product.While I again restart the project the previous products are not present there.So please help me regarding this.

C#
public partial class Default2 : System.Web.UI.Page
{
    DataTable Basket_DataTable = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["basket"] != null)
        {
            Basket_DataTable = (DataTable)Session["basket"];
        }
        else
        {
            Basket_DataTable = new DataTable();
            Basket_DataTable.Columns.Add("Id", Type.GetType("System.Int32")));
            Basket_DataTable.Columns.Add("Name", Type.GetType("System.String")));
            Basket_DataTable.Columns.Add("ImageUrl", Type.GetType("System.String")));
            Basket_DataTable.Columns.Add("Price", Type.GetType("System.Int32")));
            Basket_DataTable.Columns.Add("Item", Type.GetType("System.Int32"))););
            //Basket_DataTable.Columns.Add("total", Type.GetType("System.Int32"))););
        }
 
int id = 0;
        if (Request["DelId"] != null)
        {
            id = (int)Request["DelId"];
            DataRow() deleteRows = Basket_DataTable.Select(String.Format("Id={0}", id));
            if (deleteRows.Lenght = 1)
                    Basket_DataTable.Rows.Remove(deleteRows[0]);
        }
id = 0;
        if (Request["Id"] != null)
        {
id = (int)Request["Id"];
DataRow() findRow = Basket_DataTable.Select(String.Format("Id={0}", id));
 
            if (findRow.Length = 0) // not found
            {
                DataAccess.TestDA data = new DataAccess.TestDA();
// HERE YOU HAVE A THREAT OF SQL INJECTION - YOU SHOULD NEVER CONCATENATE SOMETHING THAT USERS CAN CHANGE!!! At the very least use HtmlServer.Encode
//Better would be to use stored procedure or parametrized query

                string sql = "Select id, name, price, imageurl, item = 1, totak = price from Products where Id=" + id.ToString;

                DataTable ret = data.exe_select(sql);
                if (ret != null && ret.Rows.Count == 1)
                {
// This will work if your basket and the row retrieved have the same columns,
// if they don't, change the select * to inlcude only relevant columns (as I did)
Basket_DataTable.ImportRow(ret);

                }
 
            }
else // found, increase the quantity of the item by one
findRow[0]["Item"] = (int)findRow[0]["Item"] +1;
        }

        Session["basket"] = Basket_DataTable;

        if (!IsPostBack)
        { // enter code here`enter code here ?!?!
            GridView2.DataSource = Basket_DataTable;
            GridView2.DataBind();
        }
 

    }
 
Share this answer
 
v2
For persistent cart you need some way to identify the user that comes back. Both solutions below will keep the cart on project restart.

You can do that in several ways, simplest of which is to add the cart products into the table
CART
having columns
cart_id uniqueidentifier
product_id int
quantity
price

then you add/delete the products into that table and you save cart_id into users Cookie[^] - assuming he accepts them (most do).

Weakness is that Cookie is bound to that single device - if the user accesses your web shop through ...laptop or tablet instead of desktop computer, he has to start over. Also, if the user accepts the cookie from some public computer (say library of internet caffe computer) - next user to go to your site will have the cart filled.
It is your responsibility as a developer to delete the cookie after the cart is emptied and to set its duration to some reasonable lenght of time (I usually set it to two weeks.



Alternative and more demanding of the user is to force the user to register on your site before buying. That way, when he logs in, you can retrieve his cart and everything is personalized for that specific user. You can keep history of his shopping, follow his orders, amount he spent on your site, his preferences etc...
This is bothersome to users and you better have the content that can keep them engaged - you can do both cookies and this. To those who bother register you offer something extra to motivate them.
 
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