none
My Shopping list datagridview not show data RRS feed

  • Question

  • Hi

    I try to build a shopping list, based in this tutorial.

    https://code.tutsplus.com/tutorials/build-a-shopping-cart-in-aspnet--net-1663

    For this i have a product, ShoppingCart and CartItem classes. When i test this build, this show everything ok between the classes but my problem begin when i change the product page to Shopping cart page. This not show data.

    My Product Class

    using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Configuration;
    namespace mrosite
    {
        public class Product
        {
            public int PCode { get; set; }
            public string PartNumber { get; set; }
            public string Description { get; set; }
            public int Available { get; set; }
            public decimal Price { get; set; }
        
    
            public Product(int pcode)
            {
            this.PCode = pcode;
                /* Begin Searh the product code into the database */
                string SqlStr = "SELECT [PCode], [PartNumber], [Description], [PStock], [Price] FROM Products WHERE PCode=@PCode";
                DataSet SqlDs = new DataSet();
                SqlCommand SqlCmd = new SqlCommand(SqlStr);
                String connStr = ConfigurationManager.ConnectionStrings["TOOLCRIB"].ConnectionString;
                SqlConnection SqlConn = new SqlConnection(connStr);
                SqlDataAdapter SqlAdap = new SqlDataAdapter();
                SqlCmd.CommandType = CommandType.Text;
                SqlCmd.Parameters.AddWithValue("@PCode", PCode);
                SqlCmd.Connection = SqlConn;
                SqlAdap.SelectCommand = SqlCmd;
                SqlAdap.Fill(SqlDs, "Prod");
                SqlConn.Close();
    
                this.PCode= Convert.ToInt32(SqlDs.Tables["Prod"].Rows[0][0]);
                this.PartNumber = SqlDs.Tables["Prod"].Rows[0][1].ToString();
                this.Description = SqlDs.Tables["Prod"].Rows[0][2].ToString();
                this.Available = Convert.ToInt32(SqlDs.Tables["Prod"].Rows[0][3]);
                this.Price = Convert.ToDecimal(SqlDs.Tables["Prod"].Rows[0][4]);
    
            }
        }
    }


    My ShoppingCart class

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace mrosite
    {
        /// <summary>
        /// Summary description for ShoppingCart
        /// </summary>
        public class ShoppingCart
        {
            #region Properties
    
            public List<CartItem> Items { get; private set; }
    
            #endregion
    
            #region Singleton Implementation
    
            // Readonly properties can only be set in initialization or in a constructor
            public static readonly ShoppingCart Instance;
    
            // The static constructor is called as soon as the class is loaded into memory
            static ShoppingCart()
            {
                // If the cart is not in the session, create one and put it there
                // Otherwise, get it from the session
                if (HttpContext.Current.Session["ASPNETShoppingCart"] == null)
                {
                    Instance = new ShoppingCart();
                    Instance.Items = new List<CartItem>();
                    HttpContext.Current.Session["ASPNETShoppingCart"] = Instance;
                }
                else
                {
                    Instance = (ShoppingCart)HttpContext.Current.Session["ASPNETShoppingCart"];
                }
            }
    
            // A protected constructor ensures that an object can't be created from outside
            protected ShoppingCart() { }
    
            #endregion
    
            #region Item Modification Methods
            /**
             * AddItem() - Adds an item to the shopping 
             */
            public void AddItem(int pCode)
            {
                // Create a new item to add to the cart
                CartItem newItem = new CartItem(pCode);
    
                // If this item already exists in our list of items, increase the quantity
                // Otherwise, add the new item to the list
                if (Items.Contains(newItem))
                {
                    foreach (CartItem item in Items)
                    {
                        if (item.Equals(newItem))
                        {
                            item.Quantity++;
                            return;
                        }
                    }
                }
                else
                {
                    newItem.Quantity = 1;
                    Items.Add(newItem);
                }
            }
    
            /**
             * SetItemQuantity() - Changes the quantity of an item in the cart
             */
            public void SetItemQuantity(int pCode, int quantity)
            {
                // If we are setting the quantity to 0, remove the item entirely
                if (quantity == 0)
                {
                    RemoveItem(pCode);
                    return;
                }
    
                // Find the item and update the quantity
                CartItem updatedItem = new CartItem(pCode);
    
                foreach (CartItem item in Items)
                {
                    if (item.Equals(updatedItem))
                    {
                        item.Quantity = quantity;
                        return;
                    }
                }
            }
    
            /**
             * RemoveItem() - Removes an item from the shopping cart
             */
            public void RemoveItem(int pCode)
            {
                CartItem removedItem = new CartItem(pCode);
                Items.Remove(removedItem);
            }
            #endregion
    
            #region Reporting Methods
            /**
             * GetSubTotal() - returns the total price of all of the items
             *                 before tax, shipping, etc.
             */
            public decimal GetSubTotal()
            {
                decimal subTotal = 0;
                foreach (CartItem item in Items)
                    subTotal += item.TotalPrice;
    
                return subTotal;
            }
            #endregion
        }
    }

    my CartItem class

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    /**
     * The CartItem Class
     * 
     * Basically a structure for holding item data
     */
    namespace mrosite
    {
        public class CartItem : IEquatable<CartItem> 
        {
            #region Properties
    
            // A place to store the quantity in the cart
            // This property has an implicit getter and setter.
            public int Quantity { get; set; }
    
            private int _productId;
            public int ProductId
            {
                get { return _productId; }
                set {
                    // To ensure that the Prod object will be re-created
                    _product = null;
                    _productId = value;
                }
            }
    
            private Product _product = null;
            public Product Prod
            {
                get {
                    // Lazy initialization - the object won't be created until it is needed
                    if (_product == null) {
                        _product = new Product(ProductId);
                    }
                    return _product;
                }
            }
            public string PartNumber
            {
                get { return Prod.PartNumber; }
            }
    
            public string Description {
                get { return Prod.Description; }
            }
    
            public int Available
            {
                get { return Prod.Available; }
            }
    
            public decimal UnitPrice {
                get { return Prod.Price; }
            }
    
            public decimal TotalPrice {
                get { return UnitPrice * Quantity; }
            }
    
            #endregion
    
            // CartItem constructor just needs a productId
            public CartItem(int productId) {
                this.ProductId = productId;
            }
    
            /**
            * Equals() - Needed to implement the IEquatable interface
            *    Tests whether or not this item is equal to the parameter
            *    This method is called by the Contains() method in the List class
            *    We used this Contains() method in the ShoppingCart AddItem() method
            */
            public bool Equals(CartItem item) {
                return item.ProductId == this.ProductId;
            }
        }
    }

    Here the item has been added in the shopping cart

    This is how i send the data to the shopping list form from products page

    protected void GrdBrowse_RowCommand1(object sender, GridViewCommandEventArgs e)
            {
                    if (e.CommandName == "SendCart")
                {
                    //Determine the RowIndex of the Row whose Button was clicked.
                    int index = Convert.ToInt32(e.CommandArgument);
    
                    //Reference the GridView Row.
                    GridViewRow row = GrdBrowse.Rows[index];
    
                    //Fetch value of Product Code
                    int myId = Convert.ToInt32(row.Cells[1].Text);
    
                    //Set value for add to shopping cart
                    Product Prod = new Product(Convert.ToInt32(row.Cells[1].Text));
    
                                   ShoppingCart.Instance.AddItem(Prod.PCode);
                    //----------------------------------------------------------------------                
                    Response.Redirect("ViewCart.aspx");
                }
    The final result



    And thanks for your help.

    Saturday, February 16, 2019 6:59 PM

All replies

  • sorry, this is the

    result

    <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="BrowseProducts.aspx.cs" Inherits="mrosite.BrowseProducts" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
            <div class="jumbotron">
            <h1>Product Finder</h1>
            <p class="lead">Search your product according with your keyword</p>
            <p>
                <asp:TextBox ID="txtScr" runat="server" Width="310px"></asp:TextBox>
                &nbsp
                <a><asp:Button ID="btnSearch" CssClass="btn btn-primary btn-lg" runat="server" Text="Search" Height="42px" Width="123px" OnClick="btnSearch_Click" /></a>
            </p>
        </div>
        <div class="container">
            
                <h3>Results...</h3>
                <p>
                    <asp:Label ID="lblResults" runat="server" Text="0 Results for: none" ForeColor="Red"></asp:Label></p>
                <p><asp:Label ID="lblShowing" runat="server" Text="0 Showing results: none" ForeColor="GrayText"></asp:Label>
                </p>
                <p>
                    <asp:GridView ID="GrdBrowse" runat="server" AutoGenerateColumns="False" AllowPaging="True" PageSize="10" EmptyDataText="There is nothing in the product list." GridLines="None" Width="100%" CellPadding="5" ShowFooter="true" 
                        DataKeyNames="PCode" OnPageIndexChanging="GrdBrowse_PageIndexChanging" OnRowCommand="GrdBrowse_RowCommand1" >
                        <HeaderStyle HorizontalAlign="Left" BackColor="#3D7169" ForeColor="#FFFFFF" />
                        <FooterStyle HorizontalAlign="Right" BackColor="#6C6B66" ForeColor="#FFFFFF" />
                        <AlternatingRowStyle BackColor="#F8F8F8" />
                        <Columns>
                            <asp:TemplateField ShowHeader="False">
                                <ItemTemplate>
                                <asp:Image runat="server" DataImageUrlField="Picture" HeaderText="Picture" ControlStyle-Width="75px" ControlStyle-Height ="75px">
                                </asp:Image>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField="PCode" HeaderText="Product Code" />
                            <asp:BoundField DataField="PN" HeaderText="Part Number" />
                            <asp:BoundField DataField="Description" HeaderText="Description" />
                            <asp:BoundField DataField="Available" HeaderText="Available" />
                            <asp:TemplateField ShowHeader="False">
                                <ItemTemplate>
                                    <asp:TextBox ID="txtQty" runat="server" Columns="5" Text="0"></asp:TextBox>  
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField ShowHeader="False">
                                <ItemTemplate>
                                    <asp:Button Text="Add to Cart" runat="server" CommandName="SendCart" CommandArgument="<%# Container.DataItemIndex %>" />
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>
                </p>
            </div>
        
    </asp:Content>
    

    Saturday, February 16, 2019 7:07 PM
  • sorry, this is the

    result

    <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="BrowseProducts.aspx.cs" Inherits="mrosite.BrowseProducts" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
            <div class="jumbotron">
            <h1>Product Finder</h1>
            <p class="lead">Search your product according with your keyword</p>
            <p>
                <asp:TextBox ID="txtScr" runat="server" Width="310px"></asp:TextBox>
                &nbsp
                <a><asp:Button ID="btnSearch" CssClass="btn btn-primary btn-lg" runat="server" Text="Search" Height="42px" Width="123px" OnClick="btnSearch_Click" /></a>
            </p>
        </div>
        <div class="container">
            
                <h3>Results...</h3>
                <p>
                    <asp:Label ID="lblResults" runat="server" Text="0 Results for: none" ForeColor="Red"></asp:Label></p>
                <p><asp:Label ID="lblShowing" runat="server" Text="0 Showing results: none" ForeColor="GrayText"></asp:Label>
                </p>
                <p>
                    <asp:GridView ID="GrdBrowse" runat="server" AutoGenerateColumns="False" AllowPaging="True" PageSize="10" EmptyDataText="There is nothing in the product list." GridLines="None" Width="100%" CellPadding="5" ShowFooter="true" 
                        DataKeyNames="PCode" OnPageIndexChanging="GrdBrowse_PageIndexChanging" OnRowCommand="GrdBrowse_RowCommand1" >
                        <HeaderStyle HorizontalAlign="Left" BackColor="#3D7169" ForeColor="#FFFFFF" />
                        <FooterStyle HorizontalAlign="Right" BackColor="#6C6B66" ForeColor="#FFFFFF" />
                        <AlternatingRowStyle BackColor="#F8F8F8" />
                        <Columns>
                            <asp:TemplateField ShowHeader="False">
                                <ItemTemplate>
                                <asp:Image runat="server" DataImageUrlField="Picture" HeaderText="Picture" ControlStyle-Width="75px" ControlStyle-Height ="75px">
                                </asp:Image>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField="PCode" HeaderText="Product Code" />
                            <asp:BoundField DataField="PN" HeaderText="Part Number" />
                            <asp:BoundField DataField="Description" HeaderText="Description" />
                            <asp:BoundField DataField="Available" HeaderText="Available" />
                            <asp:TemplateField ShowHeader="False">
                                <ItemTemplate>
                                    <asp:TextBox ID="txtQty" runat="server" Columns="5" Text="0"></asp:TextBox>  
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField ShowHeader="False">
                                <ItemTemplate>
                                    <asp:Button Text="Add to Cart" runat="server" CommandName="SendCart" CommandArgument="<%# Container.DataItemIndex %>" />
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>
                </p>
            </div>
        
    </asp:Content>


    Hi  FcoyClau,

    From your description, your question is more related to ASP.NET, I suggest you can go the ASP.NET forum for suitable support. 

    The Visual C# discuss and ask the C# programming language, IDE, libraries, samples and tools.

    Thank you for your understanding.

    Best Regards,

    Yong Lu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, February 18, 2019 5:52 AM