2 Replies - 18677 Views - Last Post: 12 March 2013 - 02:54 PM Rate Topic: -----

#1 NFS27  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 12-March 13

Shopping Cart - Add Item button - C# and ASP.NET gridview

Posted 12 March 2013 - 09:25 AM

I have created a shopping cart project using asp.net and c#. Currently i have a "Products" page with a grid view whear a list of books is automatically generated using a database. I have placed an "add to cart" button on this gridview, but what coding should i place in the c# file when the button is clicked so that the item is added to the shopping cart?

I have created 3 classes they are: CartItem, Product and Shopping Cart.

Below is the code to the "Product" asp.net page:
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<span style="font-family: Tahoma"><span style="font-size: 10pt"><strong><span style="font-size: 11pt;
color: #ff3300"><span style="color: #ff0000; text-decoration: underline">Our 
Products:</span><br />
</span>
<br />
</strong>Autograph offer a wide range of luxury and sport cars to meet any needs. View
our fleet below:<br />
&nbsp;<br />
<asp:GridView ID="Products" runat="server" AutoGenerateColumns="False" 
DataKeyNames="ProductID,ImageID" onselectedIndexChanged="Products_SelectedIndexChanged"
DataSourceID="SqlDataSource1" Height="101px" Width="600px" 
AllowPaging="True" CellPadding="4" Font-Names="Tahoma" 
GridLines="None" HorizontalAlign="Center" PageSize="4" ForeColor="#333333" 
BorderColor="White" BorderStyle="None" CellSpacing="1" >
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="ProductID" ReadOnly="True" 
SortExpression="ProductID" InsertVisible="False" Visible="false"/>
<asp:BoundField DataField="ProductName" HeaderText="Title" 
SortExpression="ProductName" />
<asp:BoundField DataField="ProductISBN" HeaderText="ISBN #" 
SortExpression="ProductISBN" />
<asp:BoundField DataField="ProductAuthor" HeaderText="Author" 
SortExpression="ProductAuthor" />
<asp:ImageField DataAlternateTextField="ISBN" DataImageUrlField="ISBN" HeaderText="Image"
DataImageUrlFormatString="~\BookImages\{0}.jpg">
<ControlStyle Height="150px" Width="100px" />
</asp:ImageField>
<asp:BoundField DataField="ProductPrice" HeaderText="Price" 
SortExpression="ProductPrice" />
<asp:BoundField DataField="ImageID" HeaderText="ImageID" InsertVisible="False" 
ReadOnly="True" SortExpression="ImageID" visible="false"/>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="AddToCart" runat="server" onclick="btnAddToCart_Click" 
Text="Add to Cart" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BackColor="#FFFBD6" BorderStyle="Solid" Font-Names="Tahoma" ForeColor="#333333"
HorizontalAlign="Center" />
<FooterStyle BackColor="#990000" BorderStyle="Solid" Font-Names="Tahoma" ForeColor="White"
HorizontalAlign="Right" Font-Bold="True" />
<PagerStyle BackColor="#FFCC66" BorderStyle="Solid" Font-Names="Tahoma" HorizontalAlign="Right" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" BorderStyle="Solid" Font-Names="Tahoma" ForeColor="Navy"
HorizontalAlign="Center" Font-Bold="True" />
<HeaderStyle BackColor="#990000" BorderStyle="Solid" Font-Bold="True" Font-Names="Tahoma"
ForeColor="White" HorizontalAlign="Center" />
<EditRowStyle BorderStyle="None" Font-Names="Tahoma" HorizontalAlign="Center" />
<AlternatingRowStyle BackColor="White" BorderStyle="Solid" Font-Names="Tahoma"
HorizontalAlign="Center" />
</asp:GridView>
</span></span>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT Products.ProductID, Products.ProductName, Products.ProductISBN, Products.ProductAuthor, Products.ProductPrice, BookImage.ImageID, BookImage.ISBN FROM Products INNER JOIN BookImage ON Products.ProductID = BookImage.ProductID" 
onselecting="SqlDataSource1_Selecting">
</asp:SqlDataSource>
<br />
</asp:Content>


the "Product" page has the following c# file:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{

}
protected void Products_SelectedIndexChanged(object sender, EventArgs e)
{

}
protected void btnAddToCart_Click(object sender, EventArgs e)
{
Response.Redirect("Shopping Cart.aspx");
}
}


Below is the "Product" class i have created:
public class Product
{
public string ProductName { get; set; }
public string ProductISBN { get; set; }
public string ProductAuthor { get; set; }
public decimal ProductPrice { get; set; }

public Product (int book)
{
string conn = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\K0815410_CI3540.mdf;Integrated Security=True;User Instance=True";
string NameConn = "SELECT ProductName FROM Products WHERE ProductID = '"+ book +"'";
string ISBNConn = "SELECT ProductISBN FROM Products WHERE ProductID = '"+ book +"'";
string AuthorConn = "SELECT ProductAuthor FROM Products WHERE ProductID = '"+ book +"'";
string PriceConn = "SELECT ProductPrice FROM Products WHERE ProductID = '"+ book +"'";

SqlConnection SqlConnection = new SqlConnection(conn);

SqlCommand SqlNameCommand = new SqlCommand(NameConn, SqlConnection);
SqlCommand SqlISBNCommand = new SqlCommand(ISBNConn, SqlConnection);
SqlCommand SqlAuthorCommand = new SqlCommand(AuthorConn, SqlConnection);
SqlCommand SqlPriceCommand = new SqlCommand(PriceConn, SqlConnection);

SqlConnection.Open();

this.ProductName = Convert.ToString(SqlNameCommand.ExecuteScalar());
this.ProductISBN = Convert.ToString(SqlISBNCommand.ExecuteScalar());
this.ProductAuthor = Convert.ToString(SqlAuthorCommand.ExecuteScalar());
this.ProductPrice = Convert.ToDecimal(SqlPriceCommand.ExecuteScalar());

SqlConnection.Close();
}
}


Below is the "CartItem" class i have created:
public class CartItem : IEquatable<CartItem>
{
public int quantity { get; set; }

private int _itemID;
public int ItemID
{
get { return _itemID; }
set { _itemID = value; }
}

private Product _book = null;
public Product Product
{
get
{
if (_book == null)
{
_book = new Product(ItemID);
}
return _book;
}
}

public string Name
{
get { return Product.ProductName; }
}

public string ISBN
{
get { return Product.ProductISBN; }
}

public string Author
{
get { return Product.ProductAuthor; }
}

public decimal Price
{
get { return Product.ProductPrice; }
}

public decimal TotalPrice
{
get { return Price * quantity; }
}

public CartItem(int BookID)
{
this.ItemID = BookID;
}

public bool Equals(CartItem book)
{
return book.ItemID == this.ItemID;
}
}


And finally below is the "Shopping Cart" class i have created:
public class ShoppingCart
{
public List<CartItem> Items { get; private set; }
public static readonly ShoppingCart Instance;

static ShoppingCart()
{
if (HttpContext.Current.Session["CSharpShoppingCart"] == null)
{
Instance = new ShoppingCart();
Instance.Items = new List<CartItem>();
HttpContext.Current.Session["CSharpShoppingCart"] = Instance;
}
else
{
Instance = (ShoppingCart)HttpContext.Current.Session["CSharpShoppingCart"];
}
}
protected ShoppingCart() { }

public void AddItem(int BookID)
{
CartItem newItem = new CartItem(BookID);

if (Items.Contains(newItem))
{
foreach (CartItem item in Items)
{
if (Items.Equals(newItem))
{
item.quantity++;
return;
}
}
}
else
{
newItem.quantity = 1;
Items.Add(newItem);
}
}

public void SetItemQuantity(int BookID, int quantity)
{
if (quantity == 0)
{
RemoveItem(BookID);
return;
}

CartItem updateItem = new CartItem(BookID);

foreach (CartItem item in Items)
{
if (item.Equals(updateItem))
{
item.quantity = quantity;
return;
}
}
}

public void RemoveItem(int BookID)
{
CartItem removeItem = new CartItem(BookID);
Items.Remove(removeItem);
}

public decimal GetSubTotal()
{
decimal subTotal = 0;
foreach (CartItem item in Items)
{
subTotal += item.TotalPrice;
}
return subTotal;
}
}



I believe that there is a problem with my "Add to Cart" button on the gridview and my classes should work fine.

I do not understand what code to put in the c# file behind the "Products" page so that when the add to cart button is clicked the selected book appears in the cart?

Is This A Good Question/Topic? 0
  • +

Replies To: Shopping Cart - Add Item button - C# and ASP.NET gridview

#2 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6091
  • View blog
  • Posts: 23,605
  • Joined: 23-August 08

Re: Shopping Cart - Add Item button - C# and ASP.NET gridview

Posted 12 March 2013 - 11:46 AM

Moved to ASP.NET
Was This Post Helpful? 0
  • +
  • -

#3 h4nnib4l  Icon User is offline

  • The Noid
  • member icon

Reputation: 1182
  • View blog
  • Posts: 1,677
  • Joined: 24-August 11

Re: Shopping Cart - Add Item button - C# and ASP.NET gridview

Posted 12 March 2013 - 02:54 PM

Woah, you're trying to do this in a really complicated fashion I think. First, why are you separating CartItem and Product? Why don't you redesign your ShoppingCart to enumerate Product instances instead? (You'll also have to add the necessary attributes from CartItem to Product, or at least decorate Product instances with those attributes before you pass them to AddItem()) Having a separate CartItem class like that just means that you're repeating code, by recreating Product attributes. Repeating yourself is bad design.

I'm not going to dig line by line through your code, but here are a few suggestions. I don't know how exactly you're adding those books to the ShoppingCart class, but I can see how the class is trying to add items; your class shouldn't be trying to read session values. Anything the class needs should be supplied by the caller. Your AddItem method should take an instance of Product as an argument, and add that directly to Items list. This is what needs to happen when you click that button, before your redirect. Don't do it directly in the event handler though: create a method to add the items, and call that method from the event handler.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1