Creating a Shopping Cart in Visual Studio 2005 using C#

Hi, as the title suggests Im trying to build a shopping cart using C# in Visual Studio 2005. Im linking my products from an access database (which Ive got to work) onto a catalogue page. The idea is that when the button on the item wanted is clicked, it is added to the shopping cart. When on the cart page I want the user to be able to add, modify and delete items.

This is my catalogue page (called default.aspx):

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>List of Items</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DataList ID="DlItems" runat="server" DataKeyField="ItemID" DataSourceID="AccessDataSource1"
            Width="411px" CellPadding="4" ForeColor="#333333" OnEditCommand="AddToCart">
            <ItemTemplate>
                ItemID:
                <asp:Label ID="ItemIDLabel" runat="server" Text='<%# Eval("ItemID") %>'></asp:Label><br />
                Name:
                <asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>'></asp:Label><br />
                Description:
                <asp:Label ID="DescriptionLabel" runat="server" Text='<%# Eval("Description") %>'>
                </asp:Label><br />
                Price:
                <asp:Label ID="PriceLabel" runat="server" Text='<%# Eval("Price") %>'></asp:Label><br />
                <br />
                <asp:Button ID="BtnAddToCart" runat="server" Text="Add to Cart" CommandName="Edit" />
            </ItemTemplate>
            <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <SelectedItemStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
            <AlternatingItemStyle BackColor="White" />
            <ItemStyle BackColor="#E3EAEB" />
            <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
        </asp:DataList><asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/JohnClarksonBand.mdb"
            SelectCommand="SELECT [ItemID], [Name], [Description], [Price] FROM [Products1]">
        </asp:AccessDataSource>
        &nbsp;
   
    </div>
    </form>
</body>
</html>


This is the c# that Ive written so far but im getting loads of errors:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        CreateCart();
    }
    public void AddToCart(Object s, DataListCommandEventArgs e)
    {
        // Get the index of the selected item into ItemID

        int ItemID = Convert.ToInt32(DlItems.DataKeys[e.Item.ItemIndex]);

        // turn it into a string and redirect to cart page
        string itemid = ItemID.ToString("ItemID");
        // Response.Redirect(UrlPropertyAttribute.GetCustomAttribute(itemid))("Cart.aspx");
        Response.Redirect("Cart.aspx?ItemId=" + itemid);
    }


    public void CreateCart()
    {
        // create the cart object
        objCartDT = (DataTable)Session["Cart"];
        // if the cart does not exist then create it
        if (objCartDT == null)
        {
            objCartDT = new DataTable("Cart");
            objCartDT.Columns.Add("CartID", typeof(Int32));
            objCartDT.Columns["CartID"].AutoIncrement = true;
            objCartDT.Columns["CartID"].AutoIncrementSeed = 1;
            objCartDT.Columns.Add("ItemID", typeof(Int32));
            objCartDT.Columns.Add("Quantity", typeof(Int32));
            objCartDT.Columns.Add("Item", typeof(string));
            objCartDT.Columns.Add("Cost", typeof(Decimal));
            // Add this cart to the session
            Session["Cart"] = objCartDT;
        }

    }
}

Can anybody help me out in getting this page to display the selected items on a cart page. Thanks in advance.
studly1_ukAsked:
Who is Participating?
 
dstanley9Commented:
If you can get the cart out of the session then you should do that in Page_Load (and not in the if (!IsPostBack()), get it on every load.  

Also, I don't think you need to declare anything except the DataTable as a page property.  So you could just have
DataTable objCartDT;

at the top and

objCartDT = Session["Cart"] as DataTable;

in your Page_Load. Then you can access it from all event handlers.
0
 
dstanley9Commented:
What kind of errors are you getting?

One sticks out right away:

        objCartDT = (DataTable)Session["Cart"];

shoudl be

        DataTable objCartDT = (DataTable)Session["Cart"];

or better

        DataTable objCartDT = Session["Cart"] as DataTable;

Also

   string itemid = ItemID.ToString("ItemID");
 should be

   string itemid = ItemID.ToString();
0
 
studly1_ukAuthor Commented:
Thanks for that, Ill credit you with some of the points picking up on those errors. On my cart page Im having some problems. This is the code:

public partial class Cart : System.Web.UI.Page
{
    //Connect to the DB
    DataAdapter
    DataSet
    DataRow
    DataTable objCartDT;
   
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Get cart out of session
            int ItemID = Convert.ToInt32(Request.QueryString["ItemID"]);
            DataSet objItemInfo = FindItem(ItemID);
           
      // if this item already exists in the cart then increase its quantity by 1
            bool blnMatch = false;
            foreach (DataRow objDR in objCartDT.Rows)
            {
                if (Convert.ToInt32(objDR["ItemID"]) == ItemID)
                {
                    int Quantity = Convert.ToInt32(objDR["Quantity"]);
                    Quantity += 1;
                    objDR["Quantity"] = Quantity;
                    blnMatch = true;
                    break;
                }
            }

            // if the item doesnt exist in the cart then add it
            if (!blnMatch)
            {
                objDR = objCartDT.NewRow();
                objDR["ItemID"] = ItemID;
                objDR["Item"] = objItemInfo.Tables["ItemInfo"].Rows[0]["ItemName"];
                objDR["Quantity"] = 1;
                objDR["Cost"] = objItemInfo.Tables["ItemInfo"].Rows[0]["Cost"];
                objCartDT.Rows.Add(objDR);
            }

            // bind the new cart to the Datagrid.
            // update the total
            lblTotal.Text = "£" + GetItemTotal();
        }
    }

    public DataSet FindItem(int ItemID)
    {
        DataSet objItemInfo = new DataSet();
        objDA = new OleDbDataAdapter("SELECT * FROM DBTABLE WHERE ItemID=" + ItemID, objConn);
        objDA.Fill(objItemInfo, "ItemInfo");
        return objItemInfo;
    }

    public Decimal GetItemTotal()
    {
        decimal decRunningTotal = 0;
        foreach (DataRow objDR in objCartDT.Rows)
        {
            decRunningTotal += Decimal.Round(Convert.ToDecimal(objDR["Cost"]) * Convert.ToInt32(objDR["Quantity"]), 2);
        }

        return decRunningTotal;
    }

    public void dgCart_Edit(Object s, DataGridCommandEventArgs e)
    {
        objCartDT = (DataTable)Session["Cart"];
        dgCart.EditItemIndex = e.Item.ItemIndex;
        dgCart.DataSource = objCartDT;
        dgCart.DataBind();
    }

    public void dgCart_Cancel(Object s, DataGridCommandEventArgs e)
    {
       
    }

    public void dgCart_Update(object s, DataGridCommandEventArgs e)
    {
        //Get Cart out of session
        TextBox txtQuantity;
        int intCartID;
        intCartID = Convert.ToInt32(dgCart.DataKeys[e.Item.ItemIndex]);
        txtQuantity = (TextBox)e.Item.FindControl("txtQuantity");

        foreach (DataRow objDR in objCartDT.Rows)
        {
            if (intCartID == (int)objDR["CartID"])
            {
                objDR["Quantity"] = Convert.ToInt32(txtQuantity.Text);
                break;
            }
        }

        lblTotal.Text = "£" + GetItemTotal();
        dgCart.EditItemIndex = -1;

       // bind the new cart to the Datagrid.
    }

    public void dgCart_Delete(Object s, DataGridCommandEventArgs e)
    {

    }

    public void ContinueShopping(Object s, EventArgs e)
    {
       
    }


0
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

 
dstanley9Commented:
   //Connect to the DB
    DataAdapter
    DataSet
    DataRow
    DataTable objCartDT;

Are you trying to define local properties?  You need to actually put in a varaible name:

    //Connect to the DB
    DataAdapter da;
    DataSet ds;
    DataRow = dr;
    DataTable objCartDT;
0
 
dstanley9Commented:
Also, several places you're using variables before they have been initialized:

objCartDT in Page_Load and dgCart_Update

Best approach is to take one error at a time and get the syntax right.  Then start debugging logic errors.
0
 
studly1_ukAuthor Commented:
Im getting 5 errors on the cart page:

Error      1      ; expected      Cart.aspx.cs      3      16
      
Error      2      Invalid token ';' in class, struct, or interface member declaration      Cart.aspx.cs      3      24

Error      3      ; expected      Cart.aspx.cs      5      12      

Error      4      ; expected      Cart.aspx.cs      7      15


Error      5      Invalid token ';' in class, struct, or interface member declaration      Cart.aspx.cs      7      24      

I dont understand why?
0
 
dstanley9Commented:
Use this syntax

    //Connect to the DB
    DataAdapter da;
    DataSet ds;
    DataRow = dr;
    DataTable objCartDT;

for the first block.  the compiler is expecting {datatype} {identifier};.  Since it doesn't find a semicolon after the first two literals, it gives you the "; expected" error.  
The rest flow from not being able to parse the code since the identifiers and keywords are now out of order.  C# doesn't necessarily treat a physical line as one line of code; one line of code can be spread over several physical lines without having to use a line break symbol (like _ in VB)
0
 
studly1_ukAuthor Commented:
Do I actually need to create a virtual database at this point? would i be right in thinking that it should be something along these lines?:

    //Connect to the DB
    DataAdapter da;
    DataSet objset = newdataset();
    DataRow  objdr;
    DataTable objCartDT = newdatatable("Cart");

Should I  have other code in my default catalogue page to have already created this?
0
 
Bob_1234Commented:
Can I have the Screen Shots of the forms and detailed code as i'm a beginner i jus want to know about the shopping cart in c#.net
0
 
studly1_ukAuthor Commented:
Sorry I no longer have the program.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.