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

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

Embed Size (px)

Citation preview

DEV305

Presenting Data with the ASP.NET DataGrid Control

Ken GetzSenior ConsultantMCW Technologies, LLC

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

Me.About

Senior Consultant with MCW Technologies

ASP.NET, VB.NET, ADO.NET, VB6 and Access video training for AppDev (www.appdev.com)

Microsoft Regional Director, SoCal

Technical editor for Access-VB-SQL Advisor magazine (www.advisor.com)

Author of several developer’s books on ASP.NET, VB, Access, and VBA

www.mcwtech.comE-mail: [email protected]

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

Introduction to the DataGrid

Supports:Sorting by column

Editing, Deleting, Selecting rows

Hyperlinked columns

Automatic/custom paging

Alternate row formatting

Templated columns

And more!

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

Using the User-Interface

Most often bind a DataGrid to a DataSet

You can write all the code by handOr 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

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 itselfYou must call the Fill method of the DataAdapter that the tools create

You get complete control over when data retrieval occurs

Try It Out!

Create a New Project

Add a SqlConnection

Add a SqlDataAdapter

Add a DataSet and Bind the DataGridSet the DataSource, DataMember, and DataKeyField properties of the grid

Use AutoFormat option to format the grid

Use the Property Builder

Property Builder provides user interface for creating complex HTML

Check out:General

Columns

Paging

Format

Borders

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

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

Using More Advanced Features

DataGrid supports:Hyperlink column

Selecting rows

Sorting columnsAscending/Descending?

Editing rows

Try it out in the completed sample

Data Binding

Now, do it all by hand!

Example keeps one Session variable:DataView: Avoids refreshing data from server

And two ViewState variablesSort: Maintains current sort expression

SortDirection: Keeps track of the current sort order

Data Binding

Look at the HandleSort procedureHandles sorting the DataView

Look at Page_LoadLoads the data

Calls FillGrid

Look at the FillGrid procedure

Setting up Columns

Bound ColumnAdd one for each bound column

Button ColumnSelect/Edit,Update,Cancel/Delete

Hyperlink ColumnCan specify TextField, URLfield and URLFormat

Use {0} for parameter

Template ColumnAllows you to supply HTML to display the column's dataRudimentary designer

Selecting Rows

Add Button ColumnSet Command Name to "Select"

Set format for SelectedItemsThis adds a SelectedItemStyle element to the HTML

Clicking the Select button at runtime changes the formatting

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}

Setting Up Paging

Allow paging (and/or custom paging)Set up page size

Show navigation buttonsSelect type and specifics

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

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 evente.SortExpression tells you the SortExpression property of the clicked column

Sorting Rows (2 of 3)

Create a sorted DataViewThen 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

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

Editing Rows

Add Edit, Cancel, Update button

Set the various text properties

Handle the EditCommand, UpdateCommand, CancelCommand events

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

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

UpdateCommand Event

Write data back to sourceat least to the DataViewand perhaps back to the real source

Update data in edited rowIf required, hook back up to the data source and save there as well

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

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

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

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

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 WithEnd IfMe.sdaDemo.Update(dv.Table)

Updating Data (6 of 6)

Clean up:

dv.RowFilter = String.EmptygrdProducts.EditItemIndex = -1FillGrid()

DeleteCommand Event

Much like UpdateCommand event handler

Delete row rather than updating data

All the other issues the same

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")

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

Community Resources

Community Resourceshttp://www.microsoft.com/communities/default.mspx

Most Valuable Professional (MVP)http://www.mvp.support.microsoft.com/

NewsgroupsConverse online with Microsoft Newsgroups, including Worldwidehttp://www.microsoft.com/communities/newsgroups/default.mspx

User GroupsMeet and learn with your peershttp://www.microsoft.com/communities/usergroups/default.mspx

Suggested Reading And Resources

The tools you need to put technology to work!The tools you need to put technology to work!

TITLETITLE AvailableAvailable

Microsoft® ASP.NET Microsoft® ASP.NET Programming with Microsoft Programming with Microsoft Visual C#® .NET Version 2003 Visual C#® .NET Version 2003 Step By Step:0-7356-1935-2Step By Step:0-7356-1935-2

TodayToday

Microsoft® ASP.NET Setup and Microsoft® ASP.NET Setup and Configuration Pocket Configuration Pocket Reference: 0-7356-1936-0Reference: 0-7356-1936-0

TodayToday

Microsoft Press books are 20% off at the TechEd Bookstore

Also buy any TWO Microsoft Press books and get a FREE T-Shirt

evaluationsevaluations

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