DataGrids, Improvedby Jesse Liberty, coauthor of Programming ASP.NET
This is the first of a series of columns in which I will be exploring the new features of Whidbey: the next generation of C#, ASP.NET, Windows Forms, and Visual Studio .NET (now known as Visual Studio 2005).
These columns are designed to give you a flavor of what we're seeing in the alpha release, and to keep you up to date as beta versions are made available. They will not be a comprehensive tutorial (that is what books are for), but rather glimpses behind the curtain.
The main topics I hope to focus on in the next few weeks include the new approach to handling data in ASP.NET and enhancements to the C# language, such as the addition of generics. For this week, I will begin by looking at building a master/detail DataGrid in ASP.NET, a non-trivial task in ASP.NET 1.1 that has become a whole lot easier in Whidbey.
Hey, Who Stole the ADO.NET Code?
In my book Programming ASP.NET, I was unable to begin the discussion of DataGrids without first describing, in some detail, the ADO.NET object model, including DataAdapters, DataTables, DataSets, and DataReaders. With Whidbey, these become less essential topics, because most of the work formerly coded by hand is now encapsulated in the DataSource controls provided for you by the framework.
Microsoft's stated goal with Whidbey was to dramatically reduce the amount of code you need to write. Now, goals like that always makes me nervous, because every time I'm offered a generic solution, I find that my particular needs are slightly different from the capability provided, and the generic solution is insufficiently flexible to handle what I want to accomplish. Since the beginning of .NET, however, Microsoft has successfully overcome this concern by making the internals readily available (you still have access to all of the ADO.NET objects, if you need them), and by providing enough events so that I can always hook into the process and tailor the response to my particular needs. So don't panic, they've made life easier, but they have not taken away our ability to do whatever we want in the application.
Creating the Application
To get started, then, you'll fire up Whidbey and create a new Web Site. Choose Visual C# as the language, and select ASP .NET Web Site. Name it MasterDetail and place it in a folder on your hard disk, as shown in Figure 1:
Figure 1. Creating the web site
Connecting to the Database
As noted above, rather than creating a DataSet or DataReader, you will make your connection to the database by using the new SqlDataSource object.
Open the Solution Explorer and find the DataConnections icon. Right-click and choose Add Connection. In the Connection tab, choose your server, enter your username and password and choose the NorthWind database, as shown in Figure 2:
Figure 2. Connecting the database
This will cause a Database connection to show in the Server Explorer window in Visual Studio .NET. Expand that connection to find the NorthWind tables, and open the Orders table. Highlight the OrderID, CustomerID, and OrderDate fields (using Control-click) and drag them onto the form.
Hey! Presto! Two objects are created for you: a SqlDataSource and a GridView. The GridView control replaces the DataGrid control we knew and loved in ASP.NET 1.x (although the DataGrid control is still available). It provides declarative syntax for a number of features that you created by hand in version 1.x (such as paging, sorting, etc.).
Before continuing, switch to Source view and take a look a the declarations of the GridView and SqlDataSource objects that have been written for you.
Switch back to design view, and click on the form (to remove the selection of the two new objects), and then click on the GridView to select it. Click the smart tab and from the Common GridView Tasks menu, select Enable Paging, Enable Sorting, and Enable Selection. As you click on these, the display changes, and a quick check of the source shows that the declaration is changed as well.
Click Edit Columns if you want to change the header of the columns in the grid (for example, to change the word "OrderDate" to the heading "Order Date," and to change the Select text from "Select" to "Details").
You might also want to click on AutoFormat to select an attractive overall format for the grid (in the example shown below, I chose Colorful 4).
Take a moment to run the application to ensure that you are getting the data you expect, and that paging, sorting, and selection are working (for now, clicking on Details will just select the row). In the next step, you will display the details of the selected record.
Displaying the Details
You could return to the data view and drag a few more columns onto the page to create a DataSource for the OrderDetails page, but let's look at another way to accomplish the same task. This time, click on the Data tab of the toolbar and drag a SqlDataSource onto your page. Display the Common SqlDataSourceTasks menu and select Configure DataSource. Choose the data connection you created earlier, and click Next. Enter the following Select, Insert, Update, and Delete statements:
SELECT [OrderID], [ProductID], [UnitPrice], [Quantity], [Discount] FROM dbo.[Order Details] where OrderID = ? INSERT INTO [Order Details] (ProductID, Quantity, Discount, OrderID) VALUES (?, ?, ?, ?) UPDATE [Order Details] SET Quantity = ?, Discount = ? WHERE ([Order Details].OrderID = ?) AND ([Order Details].ProductID = ?) DELETE FROM [Order Details] WHERE ([Order Details].OrderID = ?) AND ([Order Details].ProductID = ?)
Click the Edit Query link next to the Select statement to open the Query Editor dialog box. Click Infer Parameters to instruct the wizard to infer from your Select command what parameters will be needed (in this case, the OrderID).
You'll use the Parameter Source drop-down menu to instruct the SqlDataSource control to get its one parameter from the GridView control. To do so, choose Control in the drop-down menu, and in the Properties window, set the ControlID drop-down menu to GridView1, as shown in Figure 3:
Figure3. Editing the selection query
Clicking OK will return you to the configuration wizard, where you can set the property type to Int32 and click Finish. Your DataSource control is now configured and ready for use. You can make a connection to the database to retrieve the selected record, but you have no code (yet) to display it.
To display the data for the selected record, drag onto the page a DataList object from the Data tab of the toolbox. From the Common DetailsView Tasks menu, choose Connect To DataSource and select the DataSource object you just created. While the new DataList object has the focus, use the Properties window to set the Header Text property to Order Details.
Run the application and click on an order in the grid. Zap! The details are displayed in the DetailsView.
The only problem is that the details page shows only the first of the details records (there is a one-to-many relationship between an order and its details).
It would be great to be able to page through the details of each order. To do so, again use the Common DetailsView Tasks menu to turn on paging. In the properties window, click the plus sign next to PagerSettings and set the Mode to whichever paging mode you prefer. As you take each step, switch back to source view to examine the effect on the declaration of your control.
That's it! A nice-looking DataGrid, with pageable details, as shown in Figure 4, without writing a line of code!
Figure 4. Finished application
There is plenty to do; if nothing else, you'll want to join in the product table to display the correct product (rather than the product ID). There is always more to do, and there will be plenty of code to write, but this first exploration clearly demonstrates that Microsoft has made good on its goal of reducing the amount of "plumbing" code you must write.
Jesse Liberty is a senior program manager for Microsoft Silverlight where he is responsible for the creation of tutorials, videos and other content to facilitate the learning and use of Silverlight. Jesse is well known in the industry in part because of his many bestselling books, including O'Reilly Media's Programming .NET 3.5, Programming C# 3.0, Learning ASP.NET with AJAX and the soon to be published Programming Silverlight.
Return to ONDotnet.com