Creating Shopping Cart Example Code In Asp.Net 2.0,3.5,40 With Gridview C#.NET,VB.NET. 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>
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
Shopping Cart Example Code In ASP.NET C# VB.NET GridView
Posted by
Unknown
If you like this post than join us or share
Subscribe to:
Post Comments (Atom)
216 comments:
How to solve this error ???
"The name 'Profile' does not exist in the current context..."
TQ
@ 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>
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.
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?)
@ 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
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
@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
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.
@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
I don't know what is the issue but i am still get the same error messages.
Did anyone else try it?
@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
Download link is not working for me & this code is v. imp for me .Please help
@hanuman:
you can download the source code from this link
Click here to download
sorry for trouble , but This is a .rar extension file , i am unable to open on my computer.Please help again .
@hanuman:
You need to download and install winrar to open .rar files
alternatively download zip file from here .
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.
@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
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
@Anonymous:
Change
public partial class CartControl : System.Web.UI.Page
to
public partial class CartControl : System.Web.UI.UserControl
And error will be gone
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.
@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
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??
@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
This comment has been removed by a blog administrator.
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 .
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 ???
I"m having a problem that the cart always remembers the previous data.
Not really sure why, any suggestions?
Hi!
It's great!
But I have one question.
How to write data from Cart (grdCart) into Database (.mdf)?
hi... im suba..
when i put dot near Profile.SCart , the insert function is not available....
why?
@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;
}
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
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
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...
@anonymous:
Check whether you already having aspnet.mfd in the path you specified , if yes then delete it and try again
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....
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 .
@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 ?
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.
Please send me the .zip file .
Thank you so much
@hanuman:
Download sample code in Zip format from here
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.
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
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 .
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:
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
@hanuman:
Thanks for appreciation
@Anonymous : i m also storing and using image names in database. i couldn't get your question completely , please be more specific
Thanks for usefull information.
http://www.customsolutionsindia.com/earnmoney.html
HI,
Amit,
this is koushik ..i have seen the code for shopping cart which u have created ..i want your help for this can u tell me, Do we need to create a database table for shopping cart before we establish a connection from database..if so how and if we create a database wat options has to be included for that ...please tell me...
Thank you
@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
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.
@:KBowenProject:
Download the code from link below
http://www.box.net/shared/thh838fjhy
I understand about file but I want to learn to work VB not C# Thanks
@KBowenProject :
You can convert the C# code to VB.NET using link below
http://www.developerfusion.com/tools/convert/csharp-to-vb/
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
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
@Anonymous:
What kind of coding sample you need ?
You can download source codes of articles in this blog from the download links
@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.");
}
}
Your Download link is disabled
Your download link is disabled
Hi,
Is this session cart or database cart.
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..
Is this database cart
Hi:
Currently i'm doing a Shopping Cart for my project. It's created in asp.net 2.0 with vb. There are 3 conditions (as below) which i need to apply in :
1) Visitors Cart
Every visitor to our online shop will be given a 'Visitors Cart'. This allows the visitor to store their products in a temporary shopping cart. Once the visitor leaves the online shop, so will the contents of their shopping cart.
2) Members Cart
Every member to our online shop that logs in is given a 'Members Cart'. This allows the member to add products to their shopping cart, and come back at a later date to finalize their checkout. All products remain in their shopping cart until the member has checked them out, or removed the products themselves.
3) Info
If a member adds products to their 'Visitors Cart' and decides to log in to the online shop to use their 'Members Cart', the contents of their 'Visitors Cart' will merge with their 'Members Cart' contents automatically.
So, i'm wondering do i need to use the Session to store the Visitors Cart info and create a Member Cart table (which i already created in my sql server 2000 database) to store the Members Cart info or can use the Profile to store the info. I'm kind of confused because i'm new in asp.net 2.0.
Urgently needed help. Thanks in advanced.
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?
@Prem:
Download link is working fine , i've re checked it
@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
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
Hi Amit,
Thanks for the .zip version. I managed to extract with no problems.
Is it possible to set an expiry for the cart as the ASP.Net profile is persisted.
Regards, Neil
Is it possible to set an expiry for the cart as the asp profile is persisted.
Regards, Neil
is it possible to create a link button in the cart to delete all items?
is it possible to add a clear cart button on the USercart page?
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
Thanx a ton friend. Its great
Hari
@All :
I've updated the code , now it should work fine after login
@MSP :
Sure you can use the code
@Neil:
I've updated the code , download and check it
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?
i've tried the code,but the images do not come out...
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 :)
This comment has been removed by a blog administrator.
database.mdf is infected by trojan.
@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
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
@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
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.
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.
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
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.
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.
please can i use the same codes in asp.net webmatrix with access database
Great blog you got here. I'd like to read something more concerning that matter. Thanx for posting this info.
Sexy Lady
Call girls
Amit sir please send me the new shoppingcart with login facility at senasofnock2@gmail.com
Hello amit Jain sir, Its very helpful example of shopping cart.Sir i have another situation please help me out.
Doing this :
1)Using customprofile provider
2) want to maintain the shopping cart that the user created before login .
3) want to migrate the anonymous profile to login profile
please help me out with an example
plz eply me at: senasofnock2@gmail.com
Rakesh Kumar
India
This comment has been removed by a blog administrator.
This comment has been removed by a blog administrator.
hi this is very nice article
i used it for my project on local machine it works very well but when i upload this on hosting control center it is showing error when i add the product in to cart following is the line where i got problem please help me to solve
if (Profile.SCart == null)
{
Profile.SCart = new ShoppingCartExample.Cart();
}
Profile.SCart.Insert(ProductID, Price, 1, ProductName, ProductImageUrl);
@Sharmila:
Hi , have you uploaded the ASPNETDB.mdf to correct location ? please check it
Thanks for providing me a way to start a cart
hi!!!i hv seen ur code but can u give me the code without anonymous bcoz i don't want that .I am a student so i don't hv much experience in .net.
so Please can u help me.......
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.
thnx in advance.
sneha
This is really a cool web applet.
But I dont know why cart is not empty when I close the session and open a new session. Means though I'm a Anonymous user, when ever I load the page, it shows items already in the cart.
So to fix this I have implemented my own codes. Maybe this wont be good as the original programmer has did.
Anyway have a look on my fix:
Put this on your Product Page Server side load event:
if (this.Session.IsNewSession == true)
{
clearCart();
}
Also Below Load Event, Write this:
private void clearCart() {
if (Profile.SCart.Items.Count == 0) { }
else
{
int i = 0;
try
{
do
{
Profile.SCart.DeleteItem(i);
i++;
} while (Profile.SCart.Items.Count > 0);
}
catch
{
Profile.SCart.DeleteItem(0);
}
}
}
Hope you have got a solution for that problem!
Tekie (Maldives)
This is very nice project.Good work
Quiet good Example amiT jaiN..
BUT
Profilling perspective i'm getting much many errors. But eventhough i know profiling. I wish
to see your configurated object approach.
I'm trying to get without any error in asp.net 3.5
If you don't mind as a friend i'm asking you
pls make out without any error in any angle in
asp.net 3.5 mainly in profiling..
could you pls send me ASAP..to the below emailid
sjcmicrosoft2008@gmail.com
and
lgindiamails@gmail.com
pls amiT jaiN..Can you pls do this for me. 'cause i'm very much like your code..
plz....provide source of same example with nested gridview.....
This is simply superb..
I haven't get any errors and working good as well as i expected.
Thanks for posing.
Actually, to show the images in the products form, you should put:
"~/Images\\{0}" instead of "Images\\thumb_{0}"
also delete the thumb images from the example code.
I'm trying to download the code but Im getting this weird message:
"Because you just uploaded this file, it is still transferring to our main storage servers.
Please check back in a few moments.
If it has been more than 10 minutes since you uploaded the file, please try to upload it again. Return to previous page"
btw, excellent blog in general.
wave,
Aleleksandar
im trying to download the code but i getting this weird message:
"Because you just uploaded this file, it is still transferring to our main storage servers.
Please check back in a few moments.
If it has been more than 10 minutes since you uploaded the file, please try to upload it again. Return to previous page"
btw, excellent blog, very helpful.
wave,
aleksandar
hello
i want my datalist to recieve the query string from the previous page (the selected person name) and display the selected person image in the next page but if i do not need to httphandler like gridview (i did not want image folder like the example) may be idi not understand the example well
Sara
Can you please let me know how can i do it so that unregistered user cannot add items to the cart.
Also i'm having trouble in ProfileCommon anonymousProfile...
Please help
your database contain virus and when we run error is machineconfig is true how can we run it
Help,
Thanks for the project.
I need some help to store the profile as Binary to persist the cart after quit the application and retreive at new login as user Profile. Exist some way to store the cookie and retreive later.I have tried many times with no succes.
very nice project and also define step by step. great ho sirrrrrrrrrrrrrrrrrr
hello Sir,
i am facing problem in Button Click event for add to cart.it is throwing exception that Specified argument was out of the range of valid values.please help me
thnks in advnce.
Nice Article. How Can i Use this in my custom database rather than ASPNETDB.mdf, Plz do let me know. It's quite urgent.
Thanks
Hi,
Please send me the full code in my mail id
I am a student doing onlineshoping project please help me
ramaniranjan.niit@gmail.com
Hi
Please give complate project of shopping cart using sql server 2005
Thanks
How to write data from shoppingCart (gridviewCart) into Database
hi Amit,
What is the role of ASPNETDB.MDF kept in app_data folder? any other alternative place to put this file as i am not using app_data folder
in my application.
Thank you.
Intresting aricles you got here.
It will be intresting to find anything more concerning this topic.
Thx you for inform that information.
With best regards Agela!!
my application is running perfect on local server
but after loading on server it give error
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.
i am getting this error
The type or namespace name 'List' could not be found (are you missing a using directive or an assembly reference?)
i am getting an error
The type or namespace name 'List' could not be found (are you missing a using directive or an assembly reference?)
Thanks for your sharing.
Thanks for the great guide! I do however have a problem: this works great on my development machine, but when I move it to my hosted server I get this error: "A network-related or instance-specific error occurred while establishing a connection to SQL Server."
And the offending compiled code is:
Line 19: public virtual ShoppingCart.Cart SCart {
Line 20: get {
Line 21: return ((ShoppingCart.Cart)(this.GetPropertyValue("SCart")));
Line 22: }
Line 23: set {
Might you have any clue what is causing this?
Thanks again!
Hi I'm having an issue when I try to update the quantity on the next line item i'm getting an argumentOutofRange exception..
hi, I am unble to download the file from any of the link provided. i have tried with all browsers even like firefox, IE and chrome..
please send me the latest source code ay jollyabhi@gmail.com...
thankxxxx bro.... gr8888 work...
The type or namespace name 'Cart' does not exist in the namespace 'ShoppingCartExample' (are you missing an assembly reference?)
Hi
i got this error...
The type or namespace name 'Cart' does not exist in the namespace 'ShoppingCartExample' (are you missing an assembly reference?)
help me...
im getting this error...
Cannot implicitly convert type 'System.Web.Profile.ProfileGroupBase' to 'ProfileCommon' D:\topics\shopping\Global.asax
help me
i used your code in my project it works well.but the session is not expiring.always the added products are shown in the shopping cart.please help me how to solve this problem
hey please can i use this codes to microsoft visual web developer 2010 express?
i am using this command working well but some
coding problem are not solved
Hello,
Do you have an example of checkout page, i'm not sure what to do after i populata shopping cart.. I'm working on as school project and i don't know what's the next step...
Thanks
plz how to get tis code in VB.net??
Hi Amit,
This is Vikas rathee from Gurgaon..I am working on a project..I need a technical partner..Can you please contact me..on my email id :- vicky.rathee2005@gmail.com
or call +91 9717302595
Hi Amit,
can you send complete code..on my id
vicky.rathee2005@gmail.com
How to do this in vb.net ?
Could you tell me how to do this using vb.net ?
happy new year ^^
i have solve the problem but waiting me for i'am finish it as soon
\
what are the tables that u have used in this cart example and what are the attributes...pls help
this sample code is not working in asp.net web project means profile is not working in web porject. its only use in website.
Products and ProductDetails work fine, but when you click add to cart you get a network error, even though both Products and ProductDetails pages work fine
Exception Details: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
Line 19: public virtual ShoppingCartExample.Cart SCart {
Line 20: get {
Line 21: return ((ShoppingCartExample.Cart)(this.GetPropertyValue("SCart")));
Line 22: }
Line 23: set {
How can i put my items / images ( how can i edit db ? )
How can i change the procucts? imean , i mean to put my products ,with description etc.
can u explain how the cart is created? cz their is no cart table.
Hi i want to use this code in my project.....Can some explain me the concept of "profile" as soon as possible
Hi i want to use this code in my project..... The problem i faced was the code worked perfectly well in my lap...But when i tried to run the code in my friend's lap error occurred..."version of the aspnetdb was not correct" this is the error
so error came on accessing it. How can i correct it. Pls do help me at the earliest
Hi.
I was building a shopping cart in asp.net and this code really helped me out.
However,
after editing and updating the quantity of an item, it didn't update the changed quantity from the text box. It remains as the previous item quantity value (as what is displayed when the page was loaded).
When I debugged the code, I found out that the error is in the value inside the following textbox as in the original code. The textbox still holds the old value even though the text is already overwritten in the display.
----------------------------------------------
TextBox txtQuantity = (TextBox)
grdCart.Rows[e.RowIndex].Cells[2].Controls[0];
int Quantity = Convert.ToInt32(txtQuantity.Text);
-----------------------------------------------
I have tried a number of other ways but couldn't solve the problem. Do you have any solution regarding this problem? Thanks.
i am using visual studio 2008. i have put the above mentioned code in web.config but still i am getting errors of the profile doesnot contain in current context
hey how it maintains a log for one user
Hi Amit,
Great work.
Thanks a lot nails for your lot of work on this.
sir i want the ppt of the online shopping project in asp.net...can u plzzz send this to my id..here it is -> navreet_lehal@hotmail.com
It really use full to all.
Hi im having problems trying to implement a button, so that when click it will store the data in the gridview to the database.I really wish you could u helpout in this ><
The d/l breaks in the middle everytime...
Hi Amit,
I need to display number of total items in shopping cart in the header of each page. How can we do this using this code?
Hello Sir,
If i want to use Odbc where i have to change inside code? because i am using mysql instead of sqlserver. please help.
regards....
columb1a said...
Hello:
I have a question:
how i can do to empty the shopping cart, once i leave the navigator?
This cart works great for me. How would you handle shipping though? For example, if I wanted to do something like a single flat rate $10 shipping charge for international, but $0 for domestis using a drop down list, how can you integrate this?
Sir,
i have an error how i should handle this.i work from last 4 month on shopping cart.its my graet pleasure that u provide us.please please please help me.
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.
Line 29:
My email is kssitwar@gmail.com
Regards,
wasiq
@wasiq:
This error is caused for these reasons
1. Chekc whether u r having two web.config files in ur application ? , if yes than remove one, web.config file should be directly under virtual directory.
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
3. Remove any backup folders if you have which may contain web.config file.
4. If you have not Configured your application to run on IIS then Create a virtual directory and assign permissions to Application (Read,Write).
But above all make sure to check existance of more then one web.config files any backup folders or in any other folder
hope this helps
yes i do it successfully.
Thank u so much sir.Thank u,Thank u,Thank u,Thank u
Regard,
wasiq
Glad to know ur problem is fixed :))
Error 1 The type or namespace name 'List' could not be found (are you missing a using directive or an assembly reference?)
Error 2 The type or namespace name 'List' could not be found (are you missing a using directive or an assembly reference?)
What to do?
@Balajiv:
You need to add namespace to use List
Using System.Collections.Generic
This code is for website but doesn't work in Web Application, can you please post the code for web application also?
cn i get a code for apsx using vb as this is in c#
its a bit urgent pls
n thnx
this script example just work great...
is anyone can transfer this into session cart?
Thats really helpful dude !! Thanks a lot !
@amit
thanks
i have implement my project can help maintain session where download link for latest sample code
xception Details: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
@Above: please check your sql server connection string in web.config file,
its working fine on localhost but getting error on online...........A network-related or instance-specific error occurred while establishing a connection to SQL Server.....
@Mishel: Please check your connection string in web.config for sql server name and database name
I'm getting error shoppingcart namesapce not found
Can you show us how to connect using MySQL
Hi Amit, it's me again Cel. Can you please give me a piece of advise on checking out the products after selection? Thanks.
Regards,
Hello Amit nice Posting..
but i have a question how you create Gif?
Please tell me !
:)
I used your code it is working when i run it offline(on local host) but when i upload the files on server then it shows some database connection error
@Above: you need to change connection string in web.config according to sql server name and address of your host, and you may also need to take care of ASPNETDB.mdf
Suppose if i wnt to save the data in the cart control to a table names orders how shuold do that...
this works great on my development machine, but when I move it to my hosted server I get this error: "A network-related or instance-specific error occurred while establishing a connection to SQL Server."
And the offending compiled code is:
Line 19: public virtual ShoppingCart.Cart SCart {
Line 20: get {
Line 21: return ((ShoppingCart.Cart)(this.GetPropertyValue("SCart")));
Line 22: }
Line 23: set {
Give me reason, why its happend, very urgent...
@Phanindra: check your sql server connection string with your web host also take care of ASPNETDB connection
PLease how can I insert the data from gridview which in cartcontrol into database???
plz help me
Sarah
i want to access and store all productID of items that are in shopping cart..please give me code
In my project there are the shopping cart is always remains empty please,help me urgently....I need U'r help!!!!Please give solution fast
@Above: can you please show me the code ? then only i can find out the error
hi,anybody can help me how to create session part for the above coding?I want the shopping cart keep as temporary and will clear after user logout. Help me!. thank you.
hey amit your code is very useful. i need small help in my project i have a confrm order button at the view cart page which send the cart of individual user to admin i just want to know how to take the user cart information into confrm order button control plz reply me its urgent @ sndipsngh95@gmail.com
Hello!
This works awesome and was just what i was looking for, for my school project.
I was wondering, do you know any way to make a checkout page? Or do you got a few tips to get me going?
Thanx in advance
Hi Amit,
I have getting following error,
Parser Error Message: 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.
Source Error:
Line 9:
Line 10:
Line 11:
Line 12:
Line 13:
Hello Amit,
I want the code for Enquiry or feedback form for contact us page, in which when user have some problem then they can fill the feedback form and send it.
please help me.
@Prashant: Please check whether you are having multiple web.config in your application
refer link for more info
Amit,
How can I retrieve the items in the shopping cart and write them into my database( Product ID, Quantity, Total Price). If there's a way you are my hero ;)
Thanx, N
Amit,
There is no multiple web.config in application, and when i follow your refer link then IIS doesnt open when i had type INETMGR in run.
@Prashant: Refer Comment number 19-20 and 167-168 in this thread
other ppl also had same problem and got it fixed
Post a Comment