Saturday, May 16, 2009

Shopping cart in ASP.NET Creating Example with DataList GridView C#


Shopping cart example using C#.NET , VB.NET in ASP.NET
In this example i'm using GridView and DataList controls to create Products page and Product Details page in online shopping cart example


First of all we need to create a ShoppingCart class, for this right click on solution explorer and add new class, name it ShoppingCart.cs
Write this code in ShoppingCart.cs class
namespace ShoppingCartExample
{
    /// <summary>
    /// Summary description for ShoppingCart
    /// </summary>
    [Serializable] 
    public class CartItem
    {
        private int _productID;
        private string _productName;
        private string _imageUrl;
        private int _quantity;
        private double _price;
        private double _subTotal;

        public CartItem()
        { 
        }
        public CartItem(int ProductID, string ProductName, 
              string ImageUrl, int Quantity, double Price)
        {
            _productID = ProductID;
            _productName = ProductName;
            _imageUrl = ImageUrl;
            _quantity = Quantity;
            _price = Price;
           _subTotal = Quantity * Price;
        }
        public int ProductID
        {
            get
            {
                return _productID;
            }
            set
            {
                _productID = value;
            }
        }
         public string ProductName
         {
            get { return _productName; }
            set { _productName = value; }
         }
         public string ImageUrl
         {
             get { return _imageUrl; }
             set { _imageUrl = value; }
         }

         public int Quantity
         {
             get { return _quantity; }
             set { _quantity = value; }
         }

         public double Price
         {
             get { return _price; }
             set { _price = value; }
         }

         public double SubTotal
         {
             get { return _quantity * _price; }
            
         }
    }
    [Serializable]
    public class Cart
    {
        private DateTime _dateCreated;
        private DateTime _lastUpdate;
        private List<CartItem> _items;

        public Cart()
        {
            if (this._items == null)
            {
                this._items = new List<CartItem>();
                this._dateCreated = DateTime.Now;
            }
        }

        public List<CartItem> Items
        {
         get { return _items;}
        set { _items = value;}
        }

        public void Insert(int ProductID, double Price, 
        int Quantity, string ProductName, string ImageUrl)
        {
            int ItemIndex = ItemIndexOfID(ProductID);
            if (ItemIndex == -1)
            {
                CartItem NewItem = new CartItem();
                NewItem.ProductID = ProductID;
                NewItem.Quantity = Quantity;
                NewItem.Price = Price;
                NewItem.ProductName = ProductName;
                NewItem.ImageUrl = ImageUrl;
                _items.Add(NewItem);
            }
            else
            {
                _items[ItemIndex].Quantity += 1;
            }
            _lastUpdate = DateTime.Now;
        }

        public void Update(int RowID, int ProductID, 
                         int Quantity, double Price)
        {
            CartItem Item = _items[RowID];
            Item.ProductID = ProductID;
            Item.Quantity = Quantity;
            Item.Price = Price;
            _lastUpdate = DateTime.Now;
        }

        public void DeleteItem(int rowID)
        {
            _items.RemoveAt(rowID);
            _lastUpdate = DateTime.Now;
        }

        private int ItemIndexOfID(int ProductID)
        {
            int index = 0;
            foreach (CartItem item in _items)
            {
                if (item.ProductID == ProductID)
                {
                    return index;
                }
                index += 1;
            }
            return -1;
        }

        public double Total
        {
            get
            {
                double t = 0;
                if (_items == null)
                {
                    return 0;
                }
                foreach (CartItem Item in _items)
                {
                    t += Item.SubTotal;
                }
                return t;
            }
        }
 
    }
}

Now to create Products page, add a new webform and name it Products.aspx, add sqldataSource and configure it for select statement,
read this for how to configure SqlDataSource
Add a DataList Control on the page and make SqlDataSource1 it's source.
Configure Datalist according to below mentioned source
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ProductID], [Name], [Description], 
               [Price], [ImageUrl] FROM [Products]">
</asp:SqlDataSource>
</div>

<asp:DataList ID="DataList1" runat="server" 
              DataSourceID="SqlDataSource1" 
              RepeatColumns="4"
              RepeatDirection="Horizontal">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" 
ImageUrl='<%# Eval("ImageUrl", "Images\\thumb_{0}") %>' 
PostBackUrl='<%# Eval("ProductID", 
"ProductDetails.aspx?ProductID={0}") %>' />
<br />
<asp:Label ID="NameLabel" runat="server" 
           Text='<%# Eval("Name") %>'>
</asp:Label>
<asp:Label ID="PriceLabel" runat="server" 
           Text='<%# Eval("Price", "{0:C}") %>'>
</asp:Label><br />
<br />
<br />
</ItemTemplate>
</asp:DataList><br />
<asp:HyperLink ID="CartLink" runat="server" 
               NavigateUrl="~/UserCart.aspx">
               View Shopping Cart
</asp:HyperLink><br />
</form>

Now add a new webform and name it ProductDetails.aspx , this page is used for showing details for selected product from product catalog page, again add a SqlDataSource and DataList Control on this page and configure them according to source shown below, this time datalist is populated using QueryString Parameters.
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ProductID], [Name], [Description], 
               [Price], [ImageUrl] FROM [Products] 
               WHERE ([ProductID] = @ProductID)">
    <SelectParameters>
    <asp:QueryStringParameter Name="ProductID" 
                              QueryStringField="ProductID" 
                              Type="Decimal" />
    </SelectParameters>
</asp:SqlDataSource>
</div>

<asp:DataList ID="DataList1" runat="server" 
              DataSourceID="SqlDataSource1">
<ItemTemplate>
  <asp:Image ID="Image1" runat="server" 
       ImageUrl='<%# Eval("ImageUrl","~/Images\\{0}") %>'/>
  <asp:Label ID="ImageUrlLabel" runat="server" 
             Text='<%# Eval("ImageUrl") %>' 
             Visible="False">
  </asp:Label><br />
  <asp:Label ID="NameLabel" runat="server" 
             Text='<%# Eval("Name") %>'>
  </asp:Label><br />
  <asp:Label ID="DescriptionLabel" runat="server" 
             Text='<%# Eval("Description") %>'>
  </asp:Label><br />
  <asp:Label ID="PriceLabel" runat="server" 
             Text='<%# Eval("Price", "{0:##0.00}" ) %>'>
  </asp:Label><br />
</ItemTemplate>
</asp:DataList><br />
<asp:Button ID="btnAdd" runat="server" OnClick="Button1_Click" 
                        Text="Add to Cart" /><br /><br />
<asp:HyperLink ID="HyperLink1" runat="server" 
               NavigateUrl="~/Products.aspx">
               Return to Products Page
</asp:HyperLink>
Write this code in C# code behind of ProductDetails.aspx page
protected void Button1_Click(object sender, EventArgs e)
{
  double Price = double.Parse(((Label)
    DataList1.Controls[0].FindControl("PriceLabel")).Text);
  string ProductName = ((Label)
    DataList1.Controls[0].FindControl("NameLabel")).Text;
  string ProductImageUrl = ((Label)
   DataList1.Controls[0].FindControl("ImageUrlLabel")).Text;
int ProductID = int.Parse(Request.QueryString["ProductID"]);
if (Profile.SCart == null)
{
  Profile.SCart = new ShoppingCartExample.Cart();
}
  Profile.SCart.Insert
      (ProductID, Price, 1, ProductName, ProductImageUrl);
  Server.Transfer("Products.aspx");
}

Now right click on solution explorer and add new web user control, name it CartControl.ascx
In design view of this control add a new GridView control and a label below gridview, html shource of this control should look like this
<%@ Control Language="C#" AutoEventWireup="true" 
            CodeFile="CartControl.ascx.cs" 
            Inherits="CartControl" %>
<asp:GridView ID="grdCart" runat="server" 
              AutoGenerateColumns="False" 
              DataKeyNames="ProductID" 
              OnRowCancelingEdit="grdCart_RowCancelingEdit" 
              OnRowDeleting="grdCart_RowDeleting" 
              OnRowEditing="grdCart_RowEditing" 
              OnRowUpdating="grdCart_RowUpdating">
<Columns>
<asp:TemplateField>
    <ItemTemplate>
    <asp:Image ID="Image1" runat="server" 
    ImageUrl='<%#Eval("ImageUrl","~/Images/thumb_{0}")%>'/>
    </ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ProductName" 
                HeaderText="Product" ReadOnly="True"/>
<asp:BoundField DataField="Quantity" HeaderText="Quantity"/>
<asp:BoundField DataField="Price" DataFormatString="{0:c}" 
                HeaderText="Price" ReadOnly="True" />
<asp:BoundField DataField="SubTotal" DataFormatString="{0:c}" 
                HeaderText="Total" ReadOnly="True" />
<asp:CommandField ShowDeleteButton="True" 
                  ShowEditButton="True"/>
</Columns>
<EmptyDataTemplate>
Your Shopping Cart is empty, add items
<a href="Products.aspx">Add Products</a>
</EmptyDataTemplate>
</asp:GridView>
<asp:Label ID="TotalLabel" runat="server"></asp:Label>

Open web.config file and add this section for enabling anonymous users to add items to cart

<system.web>
  <authorization>
   <allow users="?" />
   <allow roles="admin" />
  </authorization>
  <roleManager enabled="true" />
  <authentication mode="Forms" />
          <compilation debug="true">
            </compilation>
        </system.web>
  <system.web>
    <anonymousIdentification enabled="true"/>
    <profile enabled="true">
      <properties>
       <add name="SCart" serializeAs="Binary" 
            type="ShoppingCartExample.Cart" 
            allowAnonymous="true"/>
      </properties>
    </profile>
  </system.web>

Now go to code behnd of CartControl.ascx and write this code
protected void Page_Load(object sender, EventArgs e)
    {
        if (Profile.SCart == null)
        {
            Profile.SCart = new ShoppingCartExample.Cart();
        }
        if (!Page.IsPostBack)
        {
            ReBindGrid();
        }
        if(Profile.SCart.Items == null)
        {
            TotalLabel.Visible = false;
        }
    }
    protected void grdCart_RowEditing
                 (object sender, GridViewEditEventArgs e)
    {
        grdCart.EditIndex = e.NewEditIndex;
        ReBindGrid();
    }
    protected void grdCart_RowUpdating
               (object sender, GridViewUpdateEventArgs e)
    {
        TextBox txtQuantity = (TextBox)
        grdCart.Rows[e.RowIndex].Cells[2].Controls[0];
        int Quantity = Convert.ToInt32(txtQuantity.Text);
        if (Quantity == 0)
        {
            Profile.SCart.Items.RemoveAt(e.RowIndex);
        }
        else
        {
            Profile.SCart.Items[e.RowIndex].Quantity 
                                         = Quantity;
        }
        grdCart.EditIndex = -1;
        ReBindGrid();
    }
    protected void grdCart_RowCancelingEdit
             (object sender, GridViewCancelEditEventArgs e)
    {
        grdCart.EditIndex = -1;
        ReBindGrid();
    }
    protected void grdCart_RowDeleting
                 (object sender, GridViewDeleteEventArgs e)
    {
        Profile.SCart.Items.RemoveAt(e.RowIndex);
        ReBindGrid();
    }
    private void ReBindGrid()
    {
        grdCart.DataSource = Profile.SCart.Items;
        DataBind();
        TotalLabel.Text = string.Format("Total:{0,19:C}", 
                                     Profile.SCart.Total);
    }

Now add Global Application Class (Global.asax) by right clicking on solution explorer > add new Item. and write code mentioned below in it.
void Profile_OnMigrateAnonymous(object sender, ProfileMigrateEventArgs e)
    {
        ProfileCommon anonymousProfile = Profile.GetProfile(e.AnonymousID);
        if (anonymousProfile.SCart != null)
        {
            if (Profile.SCart == null)
                Profile.SCart = new ShoppingCartExample.Cart();

            Profile.SCart.Items.AddRange(anonymousProfile.SCart.Items);

            anonymousProfile.SCart = null;
        }

        ProfileManager.DeleteProfile(e.AnonymousID);
        AnonymousIdentificationModule.ClearAnonymousIdentifier();
    }
       


Add another webform and name it UserCart.aspx, in design view of this page drag the CartControl we've just created and put a hyperlink for going back to products cataloge page

Tha's it , build and run the application
Have fun

Download the sample code attached



www.tips-fb.com
Shout it
Stumble Upon Toolbar
Submit this story to DotNetKicks vote it on WebDevVote.com add to del.icio.us saved by 0 users
Subscribe to Feeds

93 comments:

Anonymous said...

How to solve this error ???
"The name 'Profile' does not exist in the current context..."
TQ


amiT
amiT jaiN said...

@ anonymous :

have you added blow code in web.config file ?
<system.web>
<anonymousIdentification enabled="true"/>
<profile enabled="true">
<properties>
<add name="SCart" serializeAs="Binary"
type="ShoppingCartExample.Cart"
allowAnonymous="true"/>
</properties>
</profile>
</system.web>


hanuman said...

it never works sometimes profile does not exists (even i added this section to web config), sometimes some other problems.
Any code which i can get for cart to remove & edit items -getting data from a sql stored procedure .I am using table control for shoping cart & dynamically adding items .But not able to remove or edit perticular row in the table.


Bhanu said...

Is this code meant to run on vs2005 or vs2008?

and the code download link doesn't work.

in VS2008 i get the error "The name 'Profile' does not exist in the current context..." in spite of adding the lines to web.config.

in vs2005 i get the following error.
Error 1 The type or name space name 'List' could not be found (are you missing a using directive or an assembly reference?)


amiT
amiT jaiN said...

@ anonymous , hanuman and Bhanu :
I've fix the download link, download the source code , run it and do let me know if you face any further problem @ Bhanu : i've created this example using VS.NET 2005 but it should run on 2008 as well without any errors , download the source from the download link

amiT


hanuman said...

This post has been removed by a blog administrator.


Bhanu said...

Here are couple of errors that i got with the source i downloaded.
I am using VS2005. I created a Asp web application named ShoppingCartExample and copied your source to it and created a new sql data connection based on the fields u have mentioned i had already created a database and table on those fields.

I got total of 24 errors.

Error 1 ScriptManager1:Unknown server tag 'asp:ScriptManager
Error 2 The name 'DataList1' does not exist in the current context
Error 5 The name 'Profile' does not exist in the current context
Error 7 The type or namespace name 'Cart' does not exist in the namespace 'ShoppingCartExample' (are you missing an assembly reference?)
Error 13 The name 'TotalLabel' does not exist in the current context
Error 14 The name 'grdCart' does not exist in the current context

I will try on VS2008 now and see if it works


amiT
amiT jaiN said...

@Bhanu:

1 . I created this application with asp.net ajax extensions installed, you either create new AJAXEnabled website after installing ajax extensions or simply remove the script manager by going to design view and delete script manager

2. Check name of datalist control you've put on the Products page
asp:DataList ID="DataList1" runat="server"
DataSourceID="SqlDataSource1"
RepeatColumns="4"
RepeatDirection="Horizontal

For other errors check what namespace u've written in the class file in my case it's ShoppingCartExample

Add "using ShoppingCartExample" in the code behind of page


Bhanu said...

I tried it on VS2008 also petty much the same error.

1. I removed script manager.

2. I am using the same name DataList1, i didn't change ur code at all, other than configuring data source.

3. I am using the same name space as your.
but still i have issues.

Why don't you upload the complete project with .csproject file also.


amiT
amiT jaiN said...

@Bhanu: I really not able to find out why are you getting these errors

Check your Class file , and than check whether have u provided a namespace to it (u'll have to as it's not default like this

namespace ShoppingCartExample
{
Your class code
}

Any way i've uploaded a new source without ajax and with solution file and csproject file

http://www.box.net/shared/t9fq0i4x7b

Download and let me know whether it solves ur errors or not


Bhanu said...

I don't know what is the issue but i am still get the same error messages.
Did anyone else try it?


amiT
amiT jaiN said...

@bhanu :

Can you please send me your code, so that i can look into and try to fix the errors

send me ur code in zip format to jainamit.agra@gmail.com

regards


hanuman said...

Download link is not working for me & this code is v. imp for me .Please help


hanuman said...

This post has been removed by a blog administrator.


amiT
amiT jaiN said...

@hanuman:

you can download the source code from this link

Click here to download


hanuman said...

sorry for trouble , but This is a .rar extension file , i am unable to open on my computer.Please help again .


hanuman said...

This post has been removed by a blog administrator.


amiT
amiT jaiN said...

@hanuman:

You need to download and install winrar to open .rar files

alternatively download zip file from here .


hanuman said...

thanks a lot !Can you please also help me in this error-appreciate it!
It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.


amiT
amiT jaiN said...

@hanuman:

This error is caused for two reasons

1. Chekc whether u r having two web.config files in ur application ? , if yes than remove one

2. This error also occurs if u have not opened the website from the folder containing the aspx files and all files but from one folder up like this

ShoppingCartNew > shoppingCart > All files

If u browse and open ShoppingCartNew, u'll get allowDefinition='MachineToApplication' error

Open shoppingCart and u'll prolly not get this error

hope this helps


Anonymous said...

I'm getting this error:

"Make sure that the class defined in this code file matches the 'inherits' attribute, and that it extends the correct base class(e.g Page or UserControl)."

I get this erro in this line:

public partial class CartControl : System.Web.UI.Page

In this page i have in inherits:

"CodeFile="CartControl.ascx.cs"
Inherits="CartControl"

I can't see the problem, can someone help?

I'm new in asp.net


amiT
amiT jaiN said...

@Anonymous:

Change

public partial class CartControl : System.Web.UI.Page

to

public partial class CartControl : System.Web.UI.UserControl


And error will be gone


hanuman said...

Thanks a lot! it's a great code ,Question when i use ur downloaded code Profile does not give error but when i use same code creating seperate web application project Profile -does not exists error comes , even if i use Profile section in web config . file.
So are u using some reference or web reference for Profile?Please clarify for me to write code in future.


amiT
amiT jaiN said...

@Hanuman:

You must be missing something in ur code
Check all the namespaces in ur code behinds with mine

Check whether u have ASPNETDB.MDF database in ur App_Code folder , it should be created autometically when u enable profile in web.config


Anonymous said...

The profile requires a SQL Express database connection locally or the .MDF database you mentioned above. My App_Code folder does not have the ASPNETDB.MDF database in it even after I have added the profile section to my web.config. I keep getting "cannot connect to SQL database" errors when the debugger hits the profile.SCart calls because of this. How do we add the .MDF file manually??


amiT
amiT jaiN said...

@Anonymous:

Open your application in Visual Studio.
Click on Website menu > ASP.NET Configuration
Follow the steps and it should configure and create ASPNET database

Alternatively you can try adding ASPNET database froom my application

For this right click on App_Code folder > add existing Item >Browse to ASPNET.mdf > click on add


hanuman said...

Anonymous
I downloaded this code changed products data to my datatable , changed some CSS in grid ,I am doing it using "WebApplication" Not Web Site .No Error came not even for Profile as there is a MDB file sitting there in App_code folder when i downloded Jain's code ,if you are creating a new web application just copy & paste Both MDB file in your Appcode folder & set profile section in web config. Trust me it will work . It's nice code solved my problems & time too .
If you need some code i can send you my old shopping cart code in which i am using table control for cart items , but not able to remove & edit items .


Anonymous said...

This post has been removed by a blog administrator.


Anonymous said...

I"m having a problem that the cart always remembers the previous data.

Not really sure why, any suggestions?


Anonymous said...

Hi,
When i try to add the product to cart by clicking button "Add to Cart", the below error will appear...
"Cannot open user default database. Login failed."
How to solve this problem ???


Anonymous said...

Hi!
It's great!
But I have one question.
How to write data from Cart (grdCart) into Database (.mdf)?


Anonymous said...

hi... im suba..

when i put dot near Profile.SCart , the insert function is not available....

why?


amiT
amiT jaiN said...

@suba :

Please check whether you have below mentioned code in your class file or not ?

public void Insert(int ProductID, double Price,
int Quantity, string ProductName, string ImageUrl)
{
int ItemIndex = ItemIndexOfID(ProductID);
if (ItemIndex == -1)
{
CartItem NewItem = new CartItem();
NewItem.ProductID = ProductID;
NewItem.Quantity = Quantity;
NewItem.Price = Price;
NewItem.ProductName = ProductName;
NewItem.ImageUrl = ImageUrl;
_items.Add(NewItem);
}
else
{
_items[ItemIndex].Quantity += 1;
}
_lastUpdate = DateTime.Now;
}


Anonymous said...

Hi..This is Salman
its sound very cool..
but problem is that i cant able to connect database neither from sqlserver 2000 nor by VS.. By sqlserver its give error in attaching and By VS it has lost its state...
Any suggestion please..?
Please be quick its urgent ....Thanks


amiT
amiT jaiN said...

Hi salman:

I've used sql express 2005 for this application either install and use sql express 2005 or create a new database in sql server 200 with same schema of db in this application


Anonymous said...

i get the following error when i run the application...
wat could be the problem??

An error occurred during the execution of the SQL file 'InstallCommon.sql'. The SQL error number is 1802 and the SqlException message is: CREATE DATABASE failed. Some file names listed could not be created. Check related errors.
Cannot create file 'C:\DOCUMENTS AND SETTINGS\ADMINISTRATOR\MY DOCUMENTS\VISUAL STUDIO 2008\WEBSITES\MYSHOPPE\APP_DATA\ASPNETDB_TMP.MDF' because it already exists. Change the file path or the file name, and retry the operation.
Creating the ASPNETDB_f81c407bb28e41a08727ccd90245d518 database...


amiT
amiT jaiN said...

@anonymous:

Check whether you already having aspnet.mfd in the path you specified , if yes then delete it and try again


hanuman said...

Hi Amit
I am using your code but the official requirement is now with every item in the cart they can have associated Name of the person, Address, phone & location code. I added these fields in the shopping cart items and on AddToCart button storing information in two seperate datatables one item ,quantity etc. another person name ,address,phone etc. related & created nested gridview on productid ,on productid + click it gives child gridview which has related information of the parent gridview (parent has all itemchild has person name,address etc.).My question is that how can i create nested gridview like grdcart.datasource =Profile.Scart.item
in which the child gridview will have only the related Address ,name ,phone etc with productID.
with editable child gridview.AS I do not want to create datatables the way i did today & loose the beauty of Profile.cart option.Please help....


hanuman said...

can i have a nested gridview with profile with each item containing related persons name ,address location & phone numbers. As in the same page order can go to different persons .


amiT
amiT jaiN said...

@hanuman:

Hi you can achieve this thing by putting a Detailsview in usercontrol we created ,

1. Set the DataKeyNames property of GridView (grdCart) to ProductID.

2. Set ShowSelectButton property of gridview to true.

now write below mentioned code in html source of page

<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px" AutoGenerateRows="False" DataSourceID="SqlDataSource1">
<Fields>
<asp:BoundField DataField="ProductID" HeaderText="ProductID" SortExpression="ProductID" />
<asp:BoundField DataField="OrderNo" HeaderText="OrderNo" SortExpression="OrderNo" />
<asp:BoundField DataField="CustomerName" HeaderText="CustomerName" SortExpression="CustomerName" />
</Fields>
</asp:DetailsView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ProductID], [OrderNo], [CustomerName] FROM [Details] WHERE ([ProductID] = @ProductID)">
<SelectParameters>
<asp:ControlParameter ControlID="grdCart" Name="ProductID" PropertyName="SelectedValue"
Type="Decimal" />
</SelectParameters>
</asp:SqlDataSource>

I've created a sample for you which you can download from here

Do let me know whether it solves your query or not ?


hanuman said...

Amit,
I was keep posting my stuff since yesterday & my post was not there, i just check & try as you said as it is v. v. imp for me . You sent me the rar file to download again , i can only download with .zip extension , please send a .zip file.I got scared that i am out from your blog that is why me posting are not coming . please send .zip file thank you.


hanuman said...

Please send me the .zip file .
Thank you so much


amiT
amiT jaiN said...

@hanuman:

Download sample code in Zip format from
here


hanuman said...

Hi Amit ,
Actually i was able to exract from .Rar also.
Thanks a lot! everything is working fine . DetailView & my own nestedGridview (with customer order information) all with edit delete .So thanks a lot for your help on everystep.Appreciate your quick responces .


Anonymous said...

Hi. Am doing a project called as online shopping. I need to add items in cart which is stored in database, how ll i do it?


dceblog said...

Thanks for this code. One more doubt, how to add database file to project, as u have added. Do reply in this id: gjaishree4018@gmail.com


hanuman said...

good code.i tried using child gridview & edit & delete for child gridview is not working ,child gridview disappear on edit & delete.(parent gridview edit& delete is working).I tried your code with detailview but in again edit & delete not working though i wrote code for edit & delete .Request you to please suggest.


amiT
amiT jaiN said...

@dceblog:

1.If you want to create a new database than right click in solution explorer in Visual studio > select add new item > select SQL database from list, now you can create tables in this database in similar way we create in sql server.

2.If you want to add a database.mdf file from a database created in sql server than

right click on databse name in sql server management studio and select detach

Copy the databaseName.mdf and databaseName_Log files from sql server installation directory (usually C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data) to desktop

Now right click on solution explorer in Visual studio > select Add existing item > browse to databsename.mdf on desktop > click ok
Done


amiT
amiT jaiN said...

@hanuman:

Thanks for appreciation


amiT
amiT jaiN said...

@Anonymous : i m also storing and using image names in database. i couldn't get your question completely , please be more specific


Sushil said...

Thanks for usefull information.


http://www.customsolutionsindia.com/earnmoney.html


amiT
amiT jaiN said...

@koushik:

Hi koushik , i m using two databases in this application, first one is ASPNETDB.MDF
Which should be created automatically when you write the code in web.config section for enabling profiles

Second Datbase is having two tables with name Products and Details containing records of Product and their details with ImageName

You can download the source code from here


Do let me know if you are having any issues

amiT


KBowenProject said...

Hey I got download the source code. I don't like to type code C#. I want to learn VB if it look like same C# or different. I want to know thanks.


amiT
amiT jaiN said...

@:KBowenProject:

Download the code from link below

http://www.box.net/shared/thh838fjhy


KBowenProject said...

I understand about file but I want to learn to work VB not C# Thanks


amiT
amiT jaiN said...

@KBowenProject :

You can convert the C# code to VB.NET using link below

http://www.developerfusion.com/tools/convert/csharp-to-vb/


Anonymous said...

iam a .Net mobile Technology developer

Recently I started My career

could u help me as per coding

I want Some Basic CodeSamples And

in my programming we are Using sqlserver Compact Edition 3.5 for Database and visual studio 2005/2008


Anonymous said...

private void button1_Click(object sender, EventArgs e)
{
SqlCeConnection cn;
SqlCeCommand cmd = new SqlCeCommand();
SqlCeDataReader dr;
DataTable dt=new DataTable();
string constr = @"Data Source= SDCARD\SampleDB.sdf";
//cn.ConnectionString = constr ;
cn = new SqlCeConnection(constr);
cn.Open();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;

cmd.CommandText = "select usrename,password from [User] where username= '" + txtusername.Text +
"', password= '" + txtpassword.Text + "'";

if (dt.Rows.Count!=0)
{
MessageBox.Show("InValid user");
}
else
{
MessageBox.Show("valid user");
}

here i wrote code for Login form

but here i want Whoever names are in database those named persons only can login and browse but here iam getting for every user that is giving valid user may be he is in database or not

If u don't mine please help me


amiT
amiT jaiN said...

@Anonymous:

What kind of coding sample you need ?

You can download source codes of articles in this blog from the download links


amiT
amiT jaiN said...

@Anonymous:

Write login form code like this


private void btnLogin_Click(object sender, EventArgs e)
{
if (txtLogin.Text == "")
{
lblMessage.Text = "User Name cannot be blank";
}
if (txtPwd.Text == "")
{ lblMessage.Text = "Passoword cannot be blank"; }
if (txtLogin.Text != "" && txtPwd.Text.Trim()!= "")
{
CheckLogin();
}

}

private void CheckLogin()
{
string strLogin = txtLogin.Text.Trim();
string strPwd = txtPwd.Text.Trim();
try
{
string[] tables = null;
DataSet objDs = new DataSet();
string strQuery = "Select * From [User]" +
" Where username='" + strLogin.Trim().ToString().Replace("'", "''") +
"'" + " And Password='" + strPwd.ToString().Replace("'", "''") + "'";

objDs.Fill(strConnString, CommandType.Text, strQuery, objDs, tables);
if (objDs.Tables[0].Rows.Count>0 )
{
Response.Redirect("Default.aspx");

}
else
{
lblMessage.Text = "Incorrect Login information!!!";
}

}
catch (Exception ex)
{
throw new Exception("The method or operation is not implemented.");
}

}


prem said...

Your Download link is disabled


Anonymous said...

Your download link is disabled


amiT
amiT jaiN said...

@Prem:

Download link is working fine , i've re checked it


Sanjeev said...

Hi there,

I can download the .rar file but am coming up with a "CRC error" when extracting the files or accessing any og the contents. Is it corrupted? If so, could you please upload a new copy?


amiT
amiT jaiN said...

@Sanjeev:

I've checked the rar file again and it's extracting fine for me, u might be having some probs at ur end

alternatively you can download the code in ZIP FORMAT from the link below

Download shopping cart in ASP.NET source code in ZIP FORMAT

Do let me know if you still have problems


Anonymous said...

Thanx a ton friend. Its great

Hari


MSP said...

Hi, amiT jaiN
Thank you for your fantastic shopping cart instructions and codes. May I use some code in my project,which assigned by my instructor at college.

Thank you again
Hara Naoki


Anonymous said...

is it possible to create a link button in the cart to delete all items?


Anonymous said...

Is this database cart


Anonymous said...

I added the shopping cart to my project and it works great.
But I raninto a situation that when the customer want to proceed to check out , I transfer the to a login page, after login, the user should see the cart items and then pay, but somehow, after user login, the cart is empty.
And before login, the cart have 2 items.
I am not familier with the profile, would you please help me? is it something to do with the configuration? thanks a lot..


Anonymous said...

Is it possible to set an expiry for the cart as the asp profile is persisted.

Regards, Neil


Anonymous said...

Hi,

Is this session cart or database cart.


Sanjeev said...

Hi Amit,

Thanks for the .zip version. I managed to extract with no problems.


Anonymous said...

Is it possible to set an expiry for the cart as the ASP.Net profile is persisted.

Regards, Neil


Anonymous said...

Is there a way to delete all items from the Cart ie. clear cart button that can be added that perhaps sets all the quantities to 0


Anonymous said...

is it possible to add a clear cart button on the USercart page?


amiT
amiT jaiN said...

@All :

I've updated the code , now it should work fine after login


amiT
amiT jaiN said...

@MSP :

Sure you can use the code


amiT
amiT jaiN said...

@Neil:

I've updated the code , download and check it


Anonymous said...

Hi mate,
I realized that you used Profile to store anonymous user to add items to the shopping cart. Your code works great. However using profile means when a user re-visits this web, it will remind them of un-purchased items. But for most of e-commerce website, any un-purchased items should be deleted when user's session times out, otherwise the server will just keep tracking of a large amount of anonymous users and their items. Is there anyway to empty the Profile when user's session is timed out?


Anonymous said...

i've tried the code,but the images do not come out...


ZIA said...

database.mdf is infected by trojan.


Anonymous said...

hi

I want building to Mobile Shopping Cart and I am new in that


can I use this code in my work ??
are I must edit something ?

thank very much :)


ZIA said...

This post has been removed by a blog administrator.


amiT
amiT jaiN said...

@Anonymous : you can use this code

@ZIA: I've scanned and check the sample code , it's not infected at all , you need to scan your system


Anonymous said...

Hi Amit, great work indeed. I have deployed it on my local instance. works absolutely perfect. But i have a production web server where when i execute the cart.. infact when i say"Add to cart" i get the following error :

Server Error in '/' Application.
--------------------------------------------------------------------------------

The SSE Provider did not find the database file specified in the connection string. At the configured trust level (below High trust level), the SSE provider can not automatically create the database file.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Configuration.Provider.ProviderException: The SSE Provider did not find the database file specified in the connection string. At the configured trust level (below High trust level), the SSE provider can not automatically create the database file.

Source Error:

[No relevant source lines]

Source File: App_Code.4lxk39wd.1.cs Line: 24




Please note I have a main virtual directory where i have my web.config file..added anonymous and profile enabling. my aspx and code behind file resides in a sub folder.

please help. how to fix this. or if it can be used directly without the use of profiling..

thanks in advance for your time and help.

Vinay


amiT
amiT jaiN said...

@Vinay :

Hi vinay , You need to check your connection strings as error suggests,

check path of ur app_data folder where u need to put the aspnetdb.mdf file


hanuman said...

Hi Amit
I was using shopingCartExample with the same name , only change in the connection string datasource in web config . Now 1.it does not work for asp.net 3.5 profile not found .
2.If i change the name of the project give some official name to it , then also it says profile not found.
Please help .I am changing the name in web config as well.


Anonymous said...

hii nice post.I want that only registered user can use this functionality (not anonymous user).tell me how can i do this.also each user shud maintain his own shopping cart means it shud not be common.like if user1 had added 2 products then in his shopping cart only this 2 products shud be shown not any other.thnks in advanc...i hope you got my problem....
no doubt the post is very helpful...n effective.


Anonymous said...

Hi!
How is working this example with MySql and what I need to change in this code to be able use this shopping cart with MySql..
Regards


Anonymous said...

It was rather interesting for me to read this post. Thank you for it. I like such topics and anything connected to this matter. I definitely want to read a bit more soon.


Anonymous said...

It was very interesting for me to read the post. Thanks for it. I like such topics and everything connected to this matter. I definitely want to read more soon.


Anonymous said...

please can i use the same codes in asp.net webmatrix with access database


About Me

My Photo
amiT jaiN
Hi, I am amiT jaiN Software engineer working on C#.NET and ASP.NET technologies
View my complete profile

Comments

.NET Resources

Find More Articles


Subscribe To Feeds

Subscribe by E-mail

Enter your email address:

Delivered by FeedBurner


Subscribe in your favorite reader

This site is best viewed with || You may get errors in proper display of this site if using Internet explorer


C#.NET Articles and tutorials,ASP.NET Articles - blog by amiT jaiN