Asp.net| Shopping Cart
So far, I've used the DataGrid control in almost every commercial c#.net project I've ever participated in; So, when I first heard about how the GridView was improving productivity, I tried it out very quickly. Both the DataGrid and the GridView are the new control classes provided in ASP.net 2.0 that allow you to quickly and easily display tabular data, and they can be converted into client-side HTML tables for display when viewed online.
I. INTRODUCTION
This is the first article in a series of articles. In this article, we'll focus on some of the uses of the GridView control through a simple online store sample program. Note that in each article we use the same source file. To see what this example demonstrates, you only need to extract the download to a new directory on your Web server and browse to the directory name. For example, if you extract all the content into a directory "Gridviewshop" under the root directory of your Web server, and navigate to this directory:
Http://www.yourserver.com/gridviewshop
If all goes well, you should see a site as shown in Figure 1 below:
Figure 1. This series of articles online store demo snapshots. |
two. The GridView
If you've already implemented your system with a DataGrid, including your own custom paging and sorting schemes, you really don't need to consider updating to the GridView, because from a terminal effect, they all generate the same content (both generate an HTML table). However, if you are just beginning to develop a new system, then I suggest you use the GridView, especially if you want to take advantage of its built-in paging and sorting capabilities.
By setting various properties at design time, you can control the GridView from appearance to functionality. Later in this series, we'll explore these aspects in more depth by assigning some CSS classes to table rows and table column headers, and of course adding event handlers to allow users to interact with each row of data.
The fill GridView is similar to populating a DataGrid. You simply create the DataSource and then bind it to the GridView using the following code:
Mygridview.datasource = Yourdatasource; Mygridview.databind (); |
Of course, with. NET 2.0, you have another option, which is to create a SqlDataSource and bind the GridView directly to it. This is done by setting its DataSourceID to match the ID you assigned to SqlDataSource, that is:
!--Create sqldatasource--> with Mysqldatasource ID Id= "Mysqldatasource" runat= "Server" Datasourcemode= "DataReader" connectionstring= "<%$ connectionstrings:mynorthwind%>" Selectcommand= "Select LastName from Employees" > !--Create the GridView and assign its DataSourceID to match the mysqldatasource--> above Id= "MyGridView" runat= "Server" Autogeneratecolumns= "true" Datasourceid= "Mysqldatasource"/> |
As an individual, I don't value this approach much, although it's a recommended way for Microsoft to build your gridview. I prefer to have more control over my datasource because, so I can manually filter its content or even more, which is why I do not use this method in the store demo program.
OK, let's continue with the discussion of building the store demo in this article. The general situation is that there are two gridviews on one page; you've seen this image before. A GridView is used to display the product of our store, while the other content corresponds to the shopping basket. You can easily split these two parts into their respective pages, but for the sake of simplicity, we put them together.
If you open default.aspx (which is included in the corresponding zip source file in this article), you can see how the page was built. Most HTML is used only for wrapping purposes; Note the declaration at the top of the page and the main <form> label and the <GridView> label located inside it.
three. Page declaration
<%@ page inherits= "Shop.site" src= "Cs/site.aspx.cs"%> |
The page declaration simply tells us what namespace and class the page belongs to. In this example, our namespace is "shop" and our class is "site." There is also an additional attribute definition called "src" that points to an ordinary. cs text file that contains the site class.
I usually put my classes in an external. cs file during development and manually compile them into a. dll file. When I was working with Visual Studio, I was always accustomed to using precompiled DLLs during development, because later, you just needed a simple build to build them. Once I've done my job, I'll build the class into a precompiled DLL, but during development I prefer to spend more time coding rather than compiling.
Four. Building data
Id= "Gvbasket" Autogeneratecolumns= "false" Showheader= "True" Showfooter= "True" datakeynames= "id" Onrowdatabound= "Gvbasket_rowdatabound" runat= "Server" > delivery charges Total |
If you look at these two gridviews carefully, you will notice that they set the AutoGenerateColumns to False. If there is no this line, or if it is set to true, then when we bind datasource, our columns are created. By turning off 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 program, we used the ImageField and TemplateField column types. The ImageField column takes an image path as its value (through the Dataimageurlfield property), and then displays the image in its own column (when it is generated to the page).
TemplateField is the really important column. It allows you to define a headertemplate, a ItemTemplate and a footertemplate. These three tags allow you to put anything in these places. where HeaderTemplate and FooterTemplate both refer to the header and footer of the column, and ItemTemplate references the body content.
If you look at the shopping basket GridView, you will see that we have used ItemTemplate to display the name, price and quantity of each item in the basket, and then we display the shipping charges and the total price in the FooterTemplate. The above fragment displays only the "Name" column and its footer; For a complete implementation, refer to the Default.aspx source file. Because the headers for each column are static text, we use HeaderTemplate to skip over and use the TemplateField HeaderText property instead. To observe the header and footer of a GridView, you must set the Showheader and Showfooter properties of the GridView to true.
Another reason to use ItemTemplate is that you can put other HTML and. NET tags in it. In this demo program, there are several different types of tags, including <input>,
, Onrowdatabound= "Gvbasket_rowdatabound"
By contrast, the corresponding functionality of the product GridView is simpler, but it only shows how to populate ItemTemplate instead of headers or footer templates.
Five. An important function
Now, let's take a look at the main class file "Site.aspx.cs" in this sample program, located in the CS folder, and navigate to a function called Gvbasket_rowdatabound. Here is the main implementation of the function (of course, you can refer to the download source to check the 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"]); Number 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're going to do is switch on the RowType property so that we can distinguish whether we're populating a header,footer or item template, because all three of them call the same function individually. For products and shopping baskets, we've all got Datacontrolrowtype.datarow line types because this is our ItemTemplate.
Because we've identified unique IDs for all the controls in the HTML page, we can use the FindControl function in the row. This returns an "Object" if any of the controls in the row have a matching ID word. We can cast it to the object type we expect, such as a "Literal" or a "htmlinputtext" field, and then assign the data to it via its Textorvalue property. Each time a row is bound, it is passed through the Gridviewroweventargs.row property to the function. Using this technique, we are able to access the DataItem of the row, which contains all the row data from the datasource. Then it's up to us to decide what data we want to extract from it and how to use it.
In the shopping basket, we extracted the names, quantities, and prices from the DataItem, and assigned them to the related controls embedded in the 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 total value of the information generated in all the rows and the shipping costs, Rather than just the single line of data passed to the function.
Six. Conclusion
I hope that through this article, you have mastered the basics of using the GridView control and other techniques. We analyzed one way to implement the GridView control and how to control its content generation. In the next installment, we'll explore the data source for the GridView control and work with you to build the actual shopping basket.