ASP. NET 2.0 creates a shopping cart and payment system

Source: Internet
Author: User
SummaryIn this series of articles, we use ASP. NET 2.0 builds a simplified online shopping cart and PayPal system. NET 2.0, the newly introduced GridView control is studied in depth.

So far, I have participated in almost every business C #. the DataGrid control is used in the net project. Therefore, when I first heard about how the GridView improves work efficiency, I quickly tried it. Both DataGrid and GridView are ASP. NET 2.0 provides new control classes that allow you to quickly and easily display table format data, and when you watch them online, they can be converted to client HTML tables for display.

  I. Introduction

This is the first article in the series. In this article, we will focus on some usage of the GridView control through a simple online store sample program. Note that the same source file is used in each article. To observe the demo in this article, you only need to extract the downloaded content to a new directory on your web server and browse to the directory name. For example, if you extract all the content to the "gridviewshop" directory under the root directory of your web server and navigate to this directory:
Http://www.yourserver.com/gridviewshop

If everything goes well, you should see a site as shown in 1:


Figure 1. Online Store demo program snapshot in this series of articles.

  Ii. GridView

If you have used the DataGrid to implement your system, including your customized paging and sorting scheme, you do not need to consider updating it to the GridView, both generate the same content (all generate an HTML table ). However, if you are developing a new system, I suggest using the GridView, especially if you want to use its built-in paging and sorting functions.

By setting various attributes at the design time, you can control the appearance, functions, and other aspects of the GridView. Later in this series of articles, we will explore these aspects in more depth by assigning some CSS classes to table rows and table column headers. Of course, you also need to add some event processors to allow users to interact with each row of data.

Filling a GridView is similar to filling a DataGrid. You only need to create a DataSource and bind it to the GridView using the following code:

MyGridView. DataSource = yourDataSource;
MyGridView. DataBind ();

Of course, with the help of. NET 2.0, you have another option, that is, to create a SqlDataSource and bind the GridView directly to it. This is achieved by setting its performanceid to match the ID you assigned to SqlDataSource, that is:

<! -- Use the ID of mySqlDataSource to create SqlDataSource -->
<Asp: SqlDataSource
Id = "mySqlDataSource"
Runat = "server"
Performancemode = "DataReader"
ConnectionString = "<% $ ConnectionStrings: MyNorthwind %>"
SelectCommand = "SELECT LastName FROM Employees">
</Asp: SqlDataSource>
<! -- Create a GridView and assign its performanceid to match the above mySqlDataSource -->
<Asp: GridView
Id = "myGridView"
Runat = "server"
Autogeneratecolumns = "true"
Performanceid = "mySqlDataSource"/>

As a person, I don't take this method very seriously, even though it is recommended by Microsoft to create your GridView. I prefer to control more of my DataSource, because, in this way, I can manually filter its content or even more, that's why I didn't use this method in this store demo.

Okay. Let's continue to discuss how to build the shop demo in this article. Generally, there are two GridViews on a page. You can see this image in front of it. A GridView is used to display the products of our store, while other contents correspond to the shopping basket. You can easily split these two parts into their respective pages, but we put them together for simplicity.

If you open Default. aspx (which is included in the corresponding zip source file in this article), you can see how this page is created. Most HTML is only used for packaging purposes. It should be noted that the Declaration at the top of the page, the main <form> label, and the <GridView> label in it.

  3. Page Declaration

<% @ Page inherits = "shop. site" src = "cs/site. aspx. cs" %>

The page declaration simply tells us what namespace and class the page belongs. In this example, our namespace is "shop" and our class is "site ". An additional property definition called "src" also exists, pointing to a common. cs text file containing the site class.

During development, I usually put my classes in an external. cs file and manually compile them into a. dll file. When I use Visual Studio, during development, I always get used to using pre-compiled dll, because later, you only need a simple build to generate them. Once I complete the corresponding work, I will build the class into a pre-compiled dll; however, during development, I prefer to spend more time coding than compiling.

  4. Build Data

<Asp: GridView
Id = "gvBasket"
AutoGenerateColumns = "false"
ShowHeader = "True"
ShowFooter = "True"
DataKeyNames = "id"
OnRowDataBound = "gvBasket_RowDataBound"
Runat = "server">
<Columns>
<Asp: ImageField DataImageurlField = "thumb" alternatetext = "Product Thumbnail" readonly = "true"/>
<Asp: TemplateField HeaderText = "Item">
<ItemTemplate>
<H3> <asp: Literal id = "litItemName" runat = "server"/> </ItemTemplate>
<FooterTemplate>
<A href = "delivery-costs.aspx" title = "View the list of delivery charges"> Delivery Charges </a>
<Br/> <B> Total </B>
</FooterTemplate>
</Asp: TemplateField>
</Columns>
</Asp: GridView>

If you carefully observe the two GridViews, you will notice that they both set AutoGenerateColumns to false. If this row does not exist, or if it is set to true, then when we bind DataSource, our columns will be created. By disabling this feature, we can use the "Columns" sub-tag to define our own Columns. Using this feature, we can create many different types of columns. In this demo, we use the ImageField and TemplateField column types. This ImageField column uses an image path as its value (through the DataImageUrlField attribute) and then displays the image in its own column (when generated to this page ).

TemplateField is an important column. It allows you to define a HeaderTemplate, an ItemTemplate, and a FooterTemplate. These three tags allow you to place any content in these places. HeaderTemplate and FooterTemplate both reference the header and footer of the column, while ItemTemplate references the body content.

If you observe the basket GridView, you will see that we have used ItemTemplate to display the name, price, and quantity of each item in the basket. Then, we will display the shipping fee and total price in FooterTemplate. The above snippet only shows the "name" column and Its footer. for complete implementation, see the default. aspx source file. Because the header of each column is static text, we use HeaderTemplate to skip it and use the HeaderText attribute of TemplateField. To observe the header and footer of A GridView, you must set the ShowHeader and ShowFooter attributes of the GridView to True.

Another reason for using ItemTemplate is that you can place other HTML and. net tags in it. In this demo, there are several different types of labels, including <input>, <br/>, OnRowDataBound = "gvBasket_RowDataBound"

In contrast, the corresponding function of the product's GridView is simpler, but it only shows how to fill the ItemTemplate instead of the Header or Footer template.

  5. An important function

Now, let's take a look at the main class file "site. aspx. cs" in the "cs" folder in this example, and locate a function called gvBasket_RowDataBound. The following is the main implementation of the function (of course, you can refer to the download source code to check other parts of the file ):

Protected void gvBasket_RowDataBound (object sender, GridViewRowEventArgs e)
{
Switch (e. Row. RowType)
{
Case DataControlRowType. DataRow:
// Name/Description
(Literal) e. Row. FindControl ("litItemName"). Text = Convert. ToString (DataRowView) e. Row. DataItem) ["name"]);
// Quantity
String quantity = Convert. ToString (DataRowView) e. Row. DataItem) ["quantity"]);
(HtmlInputText) e. Row. FindControl ("itProductQuantity"). Value = quantity;
// Price
(Literal) e. row. findControl ("litPrice ")). text = String. format ("{0: C2}", Convert. toDouble (DataRowView) e. row. dataItem) ["price"]) * Convert. toInt32 (quantity ));
Break;
Case DataControlRowType. Footer:
DataTable dtShop = getBasketDt ();
Double total = 0.00;
For (int I = 0; I <dtShop. Rows. Count; I ++)
{
Total + = Convert. ToInt32 (dtShop. Rows [I] ["quantity"]) * Convert. ToDouble (dtShop. Rows [I] ["price"]);
}
(Literal) e. Row. FindControl ("litTotalQuantity"). Text = Convert. ToString (dtShop. Compute ("SUM (quantity )",""));
(Literal) e. row. findControl ("litDeliveryPrice ")). text = String. format ("{0: C2}", Convert. toDouble (calcDeliveryCost (total )));
(Literal) e. row. findControl ("litTotalPrice ")). text = String. format ("{0: C2}", Convert. toDouble (calcDeliveryCost (total) + total );
Break;
}
}

The first thing we need to do is to execute a switchover on the RowType attribute, so that we can distinguish whether we are filling in a Header, Footer or Item template; because all three of them call the same function independently. For products and shopping baskets, we get the DataControlRowType. DataRow row type, because this is our ItemTemplate.

Because we have identified a unique ID for all controls on the HTML page, we can use the FindControl function in the row. This will return an "Object", if any control in this row has a matched ID. We can forcibly convert it to the expected object type, such as a "Literal" or "HtmlInputText" field, and then assign the data to it through its TextorValue attribute. Each time a Row is bound, it is passed to the function through the GridViewRowEventArgs. Row attribute. With this technology, we can access the DataItem of the row, which contains all row data from DataSource. Then, it is up to us to decide what data we want to extract and how to use it.
In the shopping basket, we extract names, quantities, and prices from DataItem, and assign them to related controls embedded in ItemTemplate. For DataControlRowType. footer, the situation is basically the same, except that we extract a copy of DataSource from the session state (getBasketDt ();), because we want to use the information in all rows to generate the total value and shipping fees, it is not just a single row of data passed to the function.

  Vi. Conclusion

I hope that through this article, you have mastered the basic knowledge and other skills of using the GridView control. We have analyzed a method for implementing the GridView control and how to control its content generation. In the next article, we will explore the data source of the GridView control and work with you to create an actual shopping basket.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.