Presentation is loading. Please wait.

Presentation is loading. Please wait.

DEV305 Presenting Data with the ASP.NET DataGrid Control Ken Getz Senior Consultant MCW Technologies, LLC.

Similar presentations


Presentation on theme: "DEV305 Presenting Data with the ASP.NET DataGrid Control Ken Getz Senior Consultant MCW Technologies, LLC."— Presentation transcript:

1 DEV305 Presenting Data with the ASP.NET DataGrid Control Ken Getz Senior Consultant MCW Technologies, LLC

2

3 About This Presentation Modified from chapter in asp.net courseware Written for Application Developers Training Company http://www.appdev.com by Andy Baron, Mary Chipman, and Ken Getz

4 Me.About Senior Consultant with MCW Technologies ASP.NET, VB.NET, ADO.NET, VB6 and Access video training for AppDev (www.appdev.com)www.appdev.com Microsoft Regional Director, SoCal Technical editor for Access-VB-SQL Advisor magazine (www.advisor.com)www.advisor.com Author of several developer’s books on ASP.NET, VB, Access, and VBA www.mcwtech.com E-mail: keng@mcwtech.com

5 Objectives Learn how to set up the DataGrid control Configure DataGrid control to edit data Take advantage of some more advanced features of the DataGrid control

6 Introduction to the DataGrid Supports: Sorting by column Editing, Deleting, Selecting rows Hyperlinked columns Automatic/custom paging Alternate row formatting Templated columns And more!

7 Setting up the DataGrid Try it out: Bind a simple grid to a simple DataSet Use visual tools to create connection, data adapter, and dataset objects None of this required—just interesting and useful

8 Using the User-Interface Most often bind a DataGrid to a DataSet You can write all the code by hand Or you can use the tools provided by VS.NET Creating a DataSet requires steps: Create a connection Create a command/data adapter Fill a DataSet

9 Nothing’s Free! Unlike previous Microsoft data tools, which wrote everything for you… These tools still require at least a few lines of code The DataSet won’t fill itself You must call the Fill method of the DataAdapter that the tools create You get complete control over when data retrieval occurs

10 Try It Out! Create a New Project Add a SqlConnection Add a SqlDataAdapter Add a DataSet and Bind the DataGrid Set the DataSource, DataMember, and DataKeyField properties of the grid Use AutoFormat option to format the grid

11 Use the Property Builder Property Builder provides user interface for creating complex HTML Check out: General Columns Paging Format Borders

12 Behind the Scenes What’s going on? Property Builder is creating HTML corresponding to the properties you’ve set Take a moment to look at the page in HTML view

13 Display DataGrid You need to write a little bit of code to bind the grid to the data: If Not Page.IsPostBack Then ' Load the Data SqlDataAdapter1.Fill(DataSet11) DataGrid1.DataBind() End If

14 Using More Advanced Features DataGrid supports: Hyperlink column Selecting rows Sorting columns Ascending/Descending? Editing rows Try it out in the completed sample

15 Data Binding Now, do it all by hand! Example keeps one Session variable: DataView: Avoids refreshing data from server And two ViewState variables Sort: Maintains current sort expression SortDirection: Keeps track of the current sort order

16 Data Binding Look at the HandleSort procedure Handles sorting the DataView Look at Page_Load Loads the data Calls FillGrid Look at the FillGrid procedure

17 Setting up Columns Bound Column Add one for each bound column Button Column Select/Edit,Update,Cancel/Delete Hyperlink Column Can specify TextField, URLfield and URLFormat Use {0} for parameter Template Column Allows you to supply HTML to display the column's data Rudimentary designer

18 Selecting Rows Add Button Column Set Command Name to "Select" Set format for SelectedItems This adds a SelectedItemStyle element to the HTML Clicking the Select button at runtime changes the formatting

19 Hyperlinking In Property Builder, specify appropriate properties: Text Field: field to be displayed in the cell URL Field: field that indicates where to link URL Format String: content of the link ProductDetail.aspx?ID={0}

20 Setting Up Paging Allow paging (and/or custom paging) Set up page size Show navigation buttons Select type and specifics

21 Making Paging Happen Need to add a bit of code to make it happen In PageIndexChanged event: Private Sub grdProducts_PageIndexChanged( _ ByVal source As Object, _ ByVal e As System.Web.UI.WebControls. _ DataGridPageChangedEventArgs) _ Handles grdProducts.PageIndexChanged grdProducts.CurrentPageIndex = e.NewPageIndex FillGrid() End Sub

22 Sorting Rows (1 of 3) Set the Sort Expression property for each column Set the AllowSorting property (Behavior on the Property Builder) to True Handle SortCommand event e.SortExpression tells you the SortExpression property of the clicked column

23 Sorting Rows (2 of 3) Create a sorted DataView Then rebind the grid Sample stores sort expression and direction into ViewState variables Compares current sort to previous sort Sorts in opposite order if the expressions are the same

24 Sorting Rows (3 of 3) Code boils down to this (taken from various procedures): Dim dv As DataView ' SortExpression contains sort expression of ' selected column. strDir contains ASC/DESC. dv = DirectCast(ViewState("DataView"), DataView) dv.Sort = SortExpression & " " & strDir ' Put the data back into the grid: With grdProducts.DataSource = Session("DataView").DataBind() End WIth

25 Editing Rows Add Edit, Cancel, Update button Set the various text properties Handle the EditCommand, UpdateCommand, CancelCommand events

26 EditCommand Event Set the item to edit, and reload the grid: Private Sub grdProducts_EditCommand( _ ByVal source As Object, _ ByVal e As DataGridCommandEventArgs) _ Handles grdProducts.EditCommand grdProducts.EditItemIndex = e.Item.ItemIndex FillGrid() End Sub

27 CancelCommand Event Indicate that no row is in edit mode, and reload the grid: Private Sub grdProducts_CancelCommand( _ ByVal source As Object, _ ByVal e As DataGridCommandEventArgs) _ Handles grdProducts.CancelCommand grdProducts.EditItemIndex = -1 FillGrid() End Sub

28 UpdateCommand Event Write data back to source at least to the DataView and perhaps back to the real source Update data in edited row If required, hook back up to the data source and save there as well

29 Updating Data (1 of 6) Event receives information about selected row: Private Sub grdProducts_UpdateCommand( _ ByVal source As Object, _ ByVal e As DataGridCommandEventArgs) _ Handles grdProducts.UpdateCommand

30 Updating Data (2 of 6) Event receives information about selected row: Private Sub grdProducts_UpdateCommand( _ ByVal source As Object, _ ByVal e As DataGridCommandEventArgs) _ Handles grdProducts.UpdateCommand ByVal e As DataGridCommandEventArgs

31 Updating Data (3 of 6) Use the parameter to retrieve data from the grid: txt = DirectCast(e.Item.Cells(4).Controls(0), TextBox) unitPrice = CType(txt.Text, Decimal) txt = DirectCast(e.Item.Cells(5).Controls(0), TextBox) unitsInStock = CType(txt.Text, Decimal) ' If you know the name of the control: See templated ' version coming up later. txt = DirectCast(e.Item. _ FindControl("txtProductName"), TextBox) strProductName = txt.Text

32 Updating Data (4 of 6) Retrieve the ProductID and filter the underlying DataView to match: ' Retrieve the stored dataview, and filter it. dv = DirectCast(Session("DataView"), DataView) dv.RowFilter = "ProductID = " & _ e.Item.Cells(2).Text

33 Updating Data (5 of 6) If found row, update data and save If dv.Count > 0 Then With dv(0).Item("UnitPrice") = unitPrice.Item("UnitsInStock") = unitsInStock End With End If Me.sdaDemo.Update(dv.Table)

34 Updating Data (6 of 6) Clean up: dv.RowFilter = String.Empty grdProducts.EditItemIndex = -1 FillGrid()

35 DeleteCommand Event Much like UpdateCommand event handler Delete row rather than updating data All the other issues the same

36 Template Columns Can supply templates for a column What about hyperlink? Can't edit! Convert to templated column, and supply separate editing template Hook up data binding: DataBinder.Eval(Container.DataItem, "ProductName")

37 What to Take Away DataGrid is incredibly powerful Keeps you from having to muck with tricky HTML Provides event handling for normal data editing events Provides templated columns, so you have complete control Requires a bit of effort to master

38 Community Resources http://www.microsoft.com/communities/default.mspx Most Valuable Professional (MVP) http://www.mvp.support.microsoft.com/ Newsgroups Converse online with Microsoft Newsgroups, including Worldwide http://www.microsoft.com/communities/newsgroups/default.mspx User Groups Meet and learn with your peers http://www.microsoft.com/communities/usergroups/default.mspx

39 Suggested Reading And Resources The tools you need to put technology to work! TITLE Available Microsoft® ASP.NET Programming with Microsoft Visual C#®.NET Version 2003 Step By Step:0-7356-1935-2 Today Microsoft® ASP.NET Setup and Configuration Pocket Reference: 0-7356-1936-0 Today Microsoft Press books are 20% off at the TechEd Bookstore Also buy any TWO Microsoft Press books and get a FREE T-Shirt

40 evaluations evaluations

41 © 2003 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. MICROSOFT MAKES NO WARRANTIES, EXPRESS OR IMPLIED, IN THIS SUMMARY.


Download ppt "DEV305 Presenting Data with the ASP.NET DataGrid Control Ken Getz Senior Consultant MCW Technologies, LLC."

Similar presentations


Ads by Google