分享
 
 
 

Building an ASP.NET Shopping Cart Using DataTables

王朝asp·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

SOURCE:

http://www.sitepoint.com/article/net-shopping-cart-datatables

BEGIN:

By Zak Ruvalcaba

April 2nd 2003

Reader Rating: 8.8

Most dynamic Web applications are created for the sole purpose of making money on the Web.

Let's face it: why would you go through all the work of creating a dynamic Web application if you don't plan to make money through it? Sure, companies employ dynamic intranet sites and there are still some -- although very few -- free Web applications you can use.

In the real world, however, dynamic Web applications are created in an attempt to make money by allowing site owners to sell merchandise on the Web. Providing users with the capability to add items to a virtual shopping cart as they browse through your Website is still very much a business that commands good money. Companies such as VeriSign, Paypal, WebAssist, and LinkPoint charge to provide developers with the capability to add shopping cart functionality to their own Websites. But why pay $300-$400 for a solution that someone else already built, when you can build one just as easily yourself utilizing new technology in ASP.NET, for free?

This article will allow you to develop and implement your own shopping cart utilizing a Session, a DataGrid, and the DataTable class of the DataSet object. Through this article, you'll learn to:

Build a user interface using ASP.NET Web Server Controls

Dynamically construct a DataTable depending on user interaction

Bind the dynamically constructed DataTable to a DataGrid

Allow the user to remove items from the cart freely

Keep a running cost total of items within the cart

At the end of this article, you'll have a fully functioning shopping cart, and you'll have gained a thorough understanding of DataTables, DataGrids, and Session Variables. Download a complete demonstration of the final product here.

Learn to obtain, install and configure all the necessary software (for free) and then:

Build an ecommerce store with multiple product functionality

Integrate a PayPal credit card processing facility into your online store.

Develop a Corporate Intranet with a dynamic navigation menu.

Create a company wide email newsletter system using ASP.NET.

Build Web Forms using Web controls, validation controls, and rich controls

Download 4 Sample Chapters FREE

This project is separated into five parts:

Building the user interface

Building the DataTable structure

Adding items to the cart

Keeping a running total

Removing items from the cart

Step 1: Building the Shopping Cart User Interface

The user interface or UI for the application is quite simple. In fact, most of the interaction will occur within the DataGrid, but the UI does include some key components that the user will be interacting with:

A DropDownList Web control that will display the products that we'll offer. The cost of each item will be associated with the value of the DropDownList Web control for simplicity's sake.

A TextBox Web control that offers the user the ability to adjust quantities

A Button Web control to add to the cart

A DataGrid that will contain the cart's contents

A Label control that will display to the user a running total in terms of price

Now that you have an idea of what the UI will display, let's add these components to the body of an HTML page. Using Dreamweaver MX, we'll create a new page and add this code into the <body> tag of the page:

<form runat="server">

Product:<br>

<asp:DropDownList id="ddlProducts" runat="server">

<asp:ListItem Value="4.99">Socks</asp:ListItem>

<asp:ListItem Value="34.99">Pants</asp:ListItem>

<asp:ListItem Value="14.99">Shirt</asp:ListItem>

<asp:ListItem Value="12.99">Hat</asp:ListItem>

</asp:DropDownList><br>

Quantity:<br>

<asp:textbox id="txtQuantity" runat="server" /><br><br>

<asp:Button id="btnAdd" runat="server" Text="Add To Cart"

onClick="AddToCart" /><br><br>

<asp:DataGrid id="dg" runat="server" /><br><br>

Total:

<asp:Label id="lblTotal" runat="server" />

</form>

The code is actually quite simple and needs very little explanation. Basically, a hard-coded DropDownList control (ddlProducts) is added, with four products. The cost of those products is maintained by associating a decimal value for each specific product.

Second, a TextBox control (txtQuantity) is added so that the user can modify quantities. Next, a Button control (btnAdd) is added with the text "Add to Cart". The onClick event associated with the Button control will call the AddToCart() subroutine, which will be created in the next section.

Next, a DataGrid (dg) is added which will be used to bind to the dynamically constructed DataTable. Remember, the DataTable will be constructed in code, and bound to the DataGrid for presentation to the user. We'll add a button column to allow the user to remove a specific item if he or she wishes a little later. Finally, we'll add a Label control (lblTotal), which will be used to display to the user a running total of the items within the cart.

Step 2: Building the DataTable Structure

If you're familiar with DataSets, then you know that DataTables provide you with a way to dynamically create a purely memory-resident representation of a database table. Typically, you'd fill a DataTable from an existing database, but you could also create one programmatically, as will be the case here.

In a DataTable, columns are represented by the columns property, and rows are represented by the rows property. Thus, DataTables will be the perfect choice for the creation of our shopping cart. We can build the columns just as we would within a database, using the columns property of the DataTable, and add rows to the DataTable with the Rows property. With the DataTable built, we can then bind the DataTable to a DataGrid to display the results in an intuitive manner.

Because DataTables contain rows and columns, you will be able to effectively mock the structure of a conventional database table. The rows will be added to the DataTable as the user adds items to the cart. For now, we'll need to construct the columns that will serve as the categories for the row items. In order for the cart to function correctly, we'll need to add the following columns with a corresponding data type:

You're probably wondering how data types, auto increment, and uniqueness will be set programmatically. Remember, DataTables contain column and row properties. Some of those properties include the ability to set the above mentioned items, just as you would a traditional database table. You'll also notice that the DataTable contains a column for ID. Technically, this column has nothing to do with the shopping cart, but it will have a lot to do with keeping the items in the cart unique, and will allow us to establish a primary key if we ever want to create a relationship with another DataTable.

For now we just want the structure of the DataTable built when the page loads for the first time. We don't want to actually start to define rows until the user selects an item to add to the cart.

To begin building the cart's structure, add this code into the head of your page:

<script runat="server">

Dim objDT As System.Data.DataTable

Dim objDR As System.Data.DataRow

Private Sub Page_Load(s As Object, e As EventArgs)

If Not IsPostBack Then

makeCart()

End If

End Sub

Function makeCart()

objDT = New System.Data.DataTable("Cart")

objDT.Columns.Add("ID", GetType(Integer))

objDT.Columns("ID").AutoIncrement = True

objDT.Columns("ID").AutoIncrementSeed = 1

objDT.Columns.Add("Quantity", GetType(Integer))

objDT.Columns.Add("Product", GetType(String))

objDT.Columns.Add("Cost", GetType(Decimal))

Session("Cart") = objDT

End Function

</script>

Looking at the code, you can see, that the makeCart() function is called only when the page is loaded for the first time. This is the reason for the IsPostBack check.

Within the makeCart() function, we'll add the code that defines the actual structure for the DataTable and its columns. First, we add a column to the DataTable named ID, assigning it the data type for integer. We assign the property for AutoIncrement to True, and begin the seed at 1.

Next, add three more columns to the DataTable for Quantity, Product, and Cost, assigning them the data types for integer, string, and decimal respectively. Finally, the DataTable is added into a Session conveniently named "Cart", for storage.

That's it! If you think about the structure of a database table and then consider the structure and code for the DataTable, they begin to resemble each other conceptually. The next step involves adding items to the cart, which is no harder than defining new rows for the DataTable.

Step 3: Building the Add to Cart Functionality

Now that the structure of the DataTable has been completely built, we'll want to begin to add to the cart the specific items that the user selects from the drop down menu. Again, to do this, we simply construct new rows and add them to the appropriate position within the DataTable cart. To construct the Add to Cart functionality, add the code below:

Sub AddToCart(s As Object, e As EventArgs)

objDT = Session("Cart")

Dim Product = ddlProducts.SelectedItem.Text

objDR = objDT.NewRow

objDR("Quantity") = txtQuantity.Text

objDR("Product") = ddlProducts.SelectedItem.Text

objDR("Cost") = Decimal.Parse(ddlProducts.SelectedItem.Value)

objDT.Rows.Add(objDR)

Session("Cart") = objDT

dg.DataSource = objDT

dg.DataBind()

End Sub

You'll remember that the Button control had the onClick event that called the AddToCart() subroutine. This subroutine contains all the code that's necessary to retrieve an existing cart from the Session object if it exists, add new items to the cart, place the cart back into the session, and finally, bind to the DataGrid.

As I mentioned, the first two lines of code retrieve the cart from the session if it exists, and retrieve the product selected from the drop down menu. As you have already created a new instance of the DataRow class, you can create the new rows for the specific columns within the DataTable.

You'll notice that we set the Quantity column equal to the value of the quantity text box control, and set the Product column equal to the text value of the drop down menu selection. We then convert the value of the drop down menu, which is cost, into a decimal value for the cost column. Finally, we add the new row to the DataTable, add the DataTable to the Session, or overwrite it if it already exists, and bind the DataTable to the DataGrid.

[/url]

Learn to obtain, install and configure all the necessary software (for free) and then:

Build an ecommerce store with multiple product functionality

Integrate a PayPal credit card processing facility into your online store.

Develop a Corporate Intranet with a dynamic navigation menu.

Create a company wide email newsletter system using ASP.NET.

Build Web Forms using Web controls, validation controls, and rich controls

[url=http://advertpro.sitepoint.com:81/cgi-bin/advertpro/banners.fpl?region=34&campaign=104&name=202&publisher=0&bust=820724&timestamp=20041023203936&referrer=http%3A%2F%2F205.214.64.136%3A81&mode=RICH&redirect=http%3A%2F%2Fsitepoint.com%2Fbooks%2Faspnet1%2Fsignoff.php]Download 4 Sample Chapters FREE

Test what you have so far in the browser. It should work fine, except for one problem. You'll see that if you select an item, add it to the cart, and then select the same item again, rather than adding the sum of the old quantity with the new quantity, it just creates a new row. You can fix this problem by modifying the AddToCart() subroutine. Just below the code where you retrieve the item from the drop down menu, add the following loop to check within the DataTable for an existing product:

Dim blnMatch As Boolean = False

For Each objDR In objDT.Rows

If objDR("Product") = Product Then

objDR("Quantity") += txtQuantity.Text

blnMatch = True

Exit For

End If

Next

Now wrap the new code that adds a new row within a conditional statement.

If Not blnMatch Then

objDR = objDT.NewRow

objDR("Quantity") = Int32.Parse(txtQuantity.Text)

objDR("Product") = ddlProducts.SelectedItem.Text

objDR("Cost") = Decimal.Parse(ddlProducts.SelectedItem.Value)

objDT.Rows.Add(objDR)

End If

Basically, a new row will only be created if the product is not found within the cart. If it is found, however, it will simply adjust the quantity by whatever the user places into the quantity textbox control.

Step 4: Keeping the Order Total

The next step will be to build the function that keeps a running total of the cost of the items within the cart. This will be used to present the user with a working total as they add and remove items in the cart. You can add this functionality using the code below:

Function GetItemTotal() As Decimal

Dim intCounter As Integer

Dim decRunningTotal As Decimal

For intCounter = 0 To objDT.Rows.Count -- 1

objDR = objDT.Rows(intCounter)

decRunningTotal += (objDR("Cost") * objDR("Quantity"))

Next

Return decRunningTotal

End Function

You can see that this function simply loops through the rows in the DataTable, multiplies the quantity column by the cost column, and returns the result. The first step involves defining the functon. As you want to return a decimal value, make sure you define the function as a decimal. Next, we'll create two new variables: one as an integer and one as a decimal. Next, you loop through the rows within the DataTable and multiply the cost column for a specific row by the quantity for that row, and store it within the decRunningTotal variable. Finally, we'll return the value.

The last step will be to write the value of the function into the label control. Add the following line to the end of the btnAddToCart subroutine -- this effectively writes the cost into the label control:

lblTotal.Text = "$" & GetItemTotal()

Save your work and run it in a browser. This time, as you add items to the cart, a total is presented within the label control. Fantastic! Now, the last part we'll discuss involves removing items from the cart.

Step 5: Removing Items from the Cart

Now that a working model of the shopping cart has been constructed, we'll want to add the next bit of functionality: removing items from the cart. Obviously you can see the importance of this: you want users to be able to add and remove any and all items to or from the shopping cart as required. Add the functionality for removing items from the cart using the following subroutine:

Sub Delete_Item(s As Object, e As DataGridCommandEventArgs)

objDT = Session("Cart")

objDT.Rows(e.Item.ItemIndex).Delete()

Session("Cart") = objDT

dg.DataSource = objDT

dg.DataBind()

lblTotal.Text = "$" & GetItemTotal()

End Sub

This subroutine, which we'll associate with the DataGrid in a minute, simply dumps the contents of the session into a new DataTable object, deletes the specific row that a user clicked, and then places the revised DataTable back into the Session variable for storage. Finally we re-bind to the DataGrid and update the total by calling the GetItemTotal() function.

You'll want to note that one of the parameters being passed into the subroutine is that of the DataGridCommandEventArgs. Without this parameter, we wouldn't be able to determine which item within the DataGrid the user selected.

The last step will be to modify the DataGrid. You will need to add a new button column, as well as a new event, to call the Delete_Item subroutine. The new DataGrid should resemble the following code:

<asp:DataGrid id=dg runat="server" ondeletecommand="Delete_Item">

<columns>

<asp:buttoncolumn buttontype="LinkButton"

commandname="Delete" text="Remove Item" />

</columns>

</asp:DataGrid>

Save your work and run it in the browser. This time you can add products and remove them freely!

Summary

As you have seen, building your own shopping cart isn't very difficult. The great thing about building your own cart is that it is completely customizable -- and you don't have to spend hundreds of dollars for an extension suite that you end up having to learn anyway.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有