Click here to Skip to main content
15,904,652 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all!!

I am trying to make my first shopping cart. i googled about it and found some useful articles. now the cart is working fine but there is one problem. if i have added for example Cell phone to my cart and then i again add Cell phone it shows it has two different item in the cart when there is only one with quantity 2. how can i solve this problem ??


private void Cart()
{
   DataTable MyDT = new DataTable();
   DataRow MyRow;

   if (ViewState["DataTable"] == null)
   {
      MyDT.Columns.Add("Productid",System.Type.GetType("System.Int32"));
      MyDT.Columns.Add("ProductName");
      MyDT.Columns.Add("UnitPrice", System.Type.GetType("System.Decimal"));

      MyRow = MyDT.NewRow();

      MyRow[0] = MyDT.Rows.Count + 1;
      MyRow[1] = DropDownList1.SelectedItem.Text;
      MyRow[2] = DropDownList1.SelectedItem.Value;

      MyDT.Rows.Add(MyRow);

   }
   else
   {
      MyDT = (DataTable)ViewState["DataTable"];

      MyRow = MyDT.NewRow();

      MyRow[0] = MyDT.Rows.Count + 1;
      MyRow[1] = DropDownList1.SelectedItem.Text;
      MyRow[2] = DropDownList1.SelectedItem.Value;

      MyDT.Rows.Add(MyRow);
   }
   ViewState["DataTable"] = MyDT;
   GridView1.DataSource = MyDT;
   GridView1.DataBind();
} 
Posted
Updated 16-Dec-11 7:11am
v2

1 solution

Well in both cases you add a new row. If you want to modify an existing rows value yuo could use for example Select[^] method to first find if such product already exists in the datatable.

On the other hand having two separate rows isn't necessarily a bad thing. Each row represents a selection to the shopping cart so modifying the cart by adding and removing rows is very simple. If you want to show the amount of items in the cart grouped by product you can use for example LINQ to produce the result. For example, see: http://www.eggheadcafe.com/microsoft/Csharp/32180980/how-group-by-and-sum-values-in-datatable.aspx[^]
 
Share this answer
 
Comments
Abhinav S 16-Dec-11 13:33pm    
Good answer. My 5!
Wendelius 16-Dec-11 14:12pm    
Thanks Abhinav :)
RaviRanjanKr 16-Dec-11 15:25pm    
Nice answer, 5+
Wendelius 16-Dec-11 15:34pm    
Thanks Ravi :)

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