Creating an Online Shopping Cart and PayPal System - The GridView
(Page 2 of 4 )
If you've already implemented your system using DataGrids, including your own custom paging and sorting solutions, then you really don't need to consider updating to the GridView because, end functionality-wise, they both produce the same thing (i.e an HTML table). If however you're starting a new system, then you should go with the GridView, especially if you want to take advantage of its built-in paging and sorting abilities.
You can control several aspects of the GridView, from how it looks to how it functions, by setting various properties at design time. Later in this article series we will look into these areas more deeply by assigning some CSS classes to the table rows and table column headers, as well as adding some event handlers to allow user interactions with each row.
Populating the GridView is identical to populating a DataGrid. You create your DataSource and then bind it to the GridView with:
myGridView.DataSource = yourDataSource;
myGridView.DataBind();
With .net 2 you have another option, which is to create a SqlDataSource and bind the GridView directly to that by setting its DataSourceID to match the ID you assign to the SqlDataSource, i.e:
<!-- Create the SqlDataSource with the ID of mySqlDataSource -->
<asp:SqlDataSource
id="mySqlDataSource"
runat="server"
DataSourceMode="DataReader"
ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
SelectCommand="SELECT LastName FROM Employees">
</asp:SqlDataSource>
<!-- Create the GridView and assign its DataSourceID to match the above i.e. mySqlDataSource -->
<asp:GridView
id="myGridView"
runat="server"
autogeneratecolumns="true"
DataSourceID="mySqlDataSource"/>
Personally I'm not that keen on this method, although it is "the recommended" method by Microsoft to set up your GridView. I prefer to have more control over my DataSource so I can manually filter its contents and more, which is why we won't be using this method in the demo shop.
So let's dive into constructing the demonstration shop. The outline for the shop is that there will be two GridViews on a single page; you can see this in the introduction image. One GridView will be used to display the products in our shop and the other will be the shopping basket. You could easily split these two up onto their own pages, but for the sake of simplicity here we'll keep them together.
If you open default.aspx which is included in the zip file that accompanies this article, you can see how the page has been set up. Most of the HTML is just pretty wrapping; the bits to pay attention to are the page declaration at the top, the main <form> tag and the pair of <GridView> tags inside it.
Next: The Page Declaration >>
More C# Articles
More By Tann San