Working with the DataGrid Control - Objectives
←
→
Page content transcription
If your browser does not render page correctly, please read the page content below
Working with the DataGrid Control
Working with the
DataGrid Control
Objectives
• Learn how to set up the DataGrid control.
• Configure the DataGrid control to edit data.
• Take advantage of advanced features of the DataGrid control.
Web Pages and Web Services Professional Skills Development 7-1
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Working with the DataGrid Control
Introduction to the DataGrid
The DataGrid control is one of three controls that allow you to work with data
in an ASP.Net pagethe other two are the Repeater control and the DataList
control, which are covered in another chapter. Each of the controls is
configurable from the Visual Studio development environment, and each
control renders the HTML it needs to display its interface and data.
The DataGrid Web server control allows you to display data in a grid, or
tabular layout (it doesn’t support snaking columns). The DataGrid defaults to
displaying data in read-only mode, but you can configure it to display data in
editable controls at run time. In addition, you can create Select, Edit, Update,
and Cancel buttons that enable users to modify data. If needed, you can
configure paging and sorting for the DataGrid as well.
The DataGrid relies less on templates, and more on properties and styles. It is
much like the DataList control in that it supports selecting, editing, and
deleting data. Unlike the DataList control, however, the DataGrid control
supports templates only within columns, and unlike the DataList and Repeater
controls, the DataGrid control doesn’t require templates in order to do its
work.
The DataGrid has a rich user interface, which allows you to configure it
without writing any code, by working with its properties in the Visual Studio
environment. There’s far more to the DataGrid control than can be covered in
a single chapter. This chapter can get you started, but you’ll need to
experiment and alter the examples provided here to get the full benefit of the
DataGrid control.
7-2 Web Pages and Web Services Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Setting Up the DataGrid
Setting Up the DataGrid
See the DataGrid In order to demonstrate the simplicity and power of the DataGrid control, this
solution for the section will walk you through adding an instance of the control to a new
completed example project, and setting up the various properties you need to use in order to bind it
to a simple DataSet object.
You’ll note, as you work through this example, that we’ve elected to use some
of the user-interface-oriented data management tools provided by Visual
Studio .NET. Although the DataGrid control doesn’t require them, this seemed
as good a time as any to introduce these useful tools.
Using the User-Interface Data Tools
The DataGrid control can bind itself to various types of data sources, but
you’ll most often bind it to an ADO.NET DataSet object. Other chapters in the
course describe how to create SqlConnection (or OleDbConnection) objects,
SqlDataAdapter (or OleDbDataAdapter) objects, and DataSet objects, using
Visual Basic .NET code. And those are all valid techniques for working with
data.
Microsoft provides tools that make it even easier to create these data
management objects, and they’re especially useful when working with user-
interface controls. You’ll see, as you work through this chapter, how simple it
is to build connection strings, command text, and other data management
properties.
Just as you would require when working completely in code, creating a
DataSet visually requires several steps: You must create a connection of some
type, and a command and/or data adapter to retrieve the data. Because you’re
going to try to bind a DataGrid control to data, you’ll also need a DataSet
object. The steps in this chapter will show how you can create these objects
visually.
TIP: Data binding isn’t completely code-free. No matter how hard you try, you’ll
find that you need to write at least a few lines of code in order to bind a
DataGrid control to any data source.
Try It Out!
1. Create the project: Open Visual Studio and Choose File|New|Project. This
loads the New Project dialog box. Select Visual Basic Projects in the left
Web Pages and Web Services Professional Skills Development 7-3
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Working with the DataGrid Control
pane, and ASP.NET Web Application in the right pane, as shown in
Figure 1. Fill in the name (DataGrid) and click OK.
Figure 1. Creating a new project.
2. Add a DataGrid control: Choose View|Toolbox from the menu (or press
CTRL+ALT+X). Double-click on the DataGrid control in the Toolbox, or
drag the DataGrid control from the Web Forms tab of the Toolbox onto
the page.
Add a SqlConnection
3. Click on the Data tab in the Toolbox window, then drag a SqlConnection
object onto the page and press F4 to load the Properties window.
4. Select ConnectionString in the Properties window, click the drop-down
list, and select . Select the Northwind database on
your local SQL Server as the data source, as shown in Figure 2.
TIP: Depending on how and where you’ve installed SQL Server, you may need to
alter the settings from those we’ve used here. If in doubt, talk with your SQL
Server administrator. We will assume throughout the course that you’ve
installed SQL Server 7.0 or later on your local machine and have the
necessary permissions granted to access data in the Northwind database.
7-4 Web Pages and Web Services Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Setting Up the DataGrid
Figure 2. Specifying the SqlConnection for the DataSet.
Add a SqlDataAdapter
In order to be able to retrieve the data, you must create a SqlDataAdapter
object. In the following steps, you’ll create one visually, using the tools
provided in the Data Toolbox.
Web Pages and Web Services Professional Skills Development 7-5
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Working with the DataGrid Control
1. From the Data tab on the Toolbox, drag a SqlDataAdapter onto the form.
Walk through the Data Adaptor Configuration Wizard to select the
SqlConnection and Use SQL Statements options.
2. On the Generate the SQL Statements page, click Query Builder to load
the Products table from the Northwind database into the query builder, as
shown in Figure 3. Select the ProductID, ProductName, UnitPrice, and
UnitsInStock columns. (If you right-click on the dialog box and select
Run from the context menu, you’ll see the actual data, as shown in Figure
3.)
3. Sort by ProductName and click OK.
Figure 3. Building a query for the SqlDataAdapter.
4. Click Advanced Options, and deselect the Generate Insert, Update, and
Delete Statements option. This example doesn’t require these features.
Click OK to close the dialog box.
5. Click Finish to complete the steps required to create the SqlDataAdapter.
Add a Dataset and Bind the DataGrid
You’ll need a DataSet object in order to display the data in your DataGrid
control. Although you can create a standard DataSet object in code, Visual
Studio .NET provides the capability of creating a Typed DataSet. A Typed
7-6 Web Pages and Web Services Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Setting Up the DataGrid
DataSet is a class that encapsulates the behavior of a DataSet, providing
properties corresponding to each of the fields in the data source. Although
using a Typed DataSet isn’t required, it makes it a lot easier to bind the
DataGrid to your data. Without this extra step, you would have to create the
DataSet in code.
Try It Out!
Follow these steps to create a Typed DataSet and bind the DataGrid control to
the new DataSet:
1. Right-click on the SqlDataAdapter1 object, and select Generate DataSet
from its context menu. In the Generate Dataset dialog box, shown in
Figure 4, note that the SqlDataAdapter you created in an earlier step is
already selected. Click OK. This creates a DataSet named DataSet11.
Figure 4. Adding a Dataset based on the SqlDataAdapter.
Web Pages and Web Services Professional Skills Development 7-7
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Working with the DataGrid Control
2. Select the DataGrid control and set its DataSource property to
Dataset11, as shown in Figure 5. Set the DataMember to Products, and
the DataKeyField to ProductID (this tells the DataGrid which field is the
primary key).
Figure 5. Setting the DataGrid’s DataSource property to the DataSet.
TIP: Because a DataSet object can contain multiple DataTable objects, you may
need to indicate which table you want to display by setting the DataMember
property of the DataGrid. In this case, your DataSet contained only one
DataTable, but it’s still a good idea to indicate which DataTable you need.
7-8 Web Pages and Web Services Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Setting Up the DataGrid
3. Once you set the DataGrid’s DataSource property, the DataGrid control
generates a bound column for each field in the data source. Each field in
the data source is rendered in a separate column, in the order it occurs in
the data source. Field names appear in the grid’s column headers, and
values are rendered in text labels, as shown in Figure 6.
Figure 6. The page in Design view has column information filled in once the
DataSource property for the DataGrid is set.
4. Apply some formatting by right-clicking on the DataGrid and choosing
Auto Format from the menu. Select one of the formats shown in Figure 7.
Click OK.
Figure 7. Use AutoFormat to quickly apply formatting to the DataGrid.
Use the Property Builder
You’ll most likely want to control the behavior and layout of the grid more
carefully than you can by simply selecting data and a formatting style. In order
Web Pages and Web Services Professional Skills Development 7-9
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Working with the DataGrid Control
to get that control, you can either manipulate the HTML for the page manually,
or you can use the Property Builder provided by Visual Studio .NET. The
Property Builder’s a lot easier, and this section walks you through setting more
properties of the DataGrid control, using the Property Builder dialog box.
Try It Out!
Follow these steps to configure the columns in the DataGrid control:
1. Right-click on the grid and choose Property Builder. This enables you to
customize the display of the DataGrid, as shown in Figure 8. In this dialog
box, make sure the Show header and Allow sorting options are selected.
NOTE Even though you’ve selected the option to allow sorting, no
sorting occurs automatically. You’ll learn how to write code to
implement this feature later in the chapter.
Figure 8. Setting additional options for the DataGrid.
7-10 Web Pages and Web Services Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Setting Up the DataGrid
2. Click the Columns node at the left side of the DataGrid1 Properties dialog
box to display the properties for the grid’s columns. Clear the Create
columns automatically at runtime option (see Figure 9). Rather than
having the grid select the columns, you’re going to do it manually.
TIP: The DataGrid can be configured to pull in data automatically from a data
source. If you do this, however, your grid will contain all the columns
contained within the data source. In the examples here, we’ve elected to turn
off this option and define the columns manually.
3. Select the (All Fields) node from the Available Columns list, then click >
to copy all the fields to the Selected Columns list. Highlight each in turn,
modifying the Header Text for each, as you see fit.
4. For each column, set the Sort expression to be the column itself, and
perhaps add spaces to the Header text so that the names are more readable.
In addition, you can set a Data formatting expression for the fields. For
example, you might enter {0:C} to force formatting as currency. Figure 9
shows UnitPrice with a Data formatting expression set to display the field
as currency.
TIP: Under the covers, the page will use the {0:C} as a replaceable formatting
parameter The “0” indicates that this is the replacement for the 0th parameter
(starting with 0, of course), and the “:C” indicates the formatting to use for
the parameter. For more information on formatting numbers, look in the
online help, searching for the topic “Standard Numeric Format Strings.”
Web Pages and Web Services Professional Skills Development 7-11
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Working with the DataGrid Control
Figure 9. Setting column display properties.
7-12 Web Pages and Web Services Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Setting Up the DataGrid
5. Click the Paging node to manually configure paging for the DataGrid. For
this example paging is turned off, as shown in Figure 10. You’ll learn how
to control paging later in this chapter.
Figure 10. Configuring paging for the DataGrid.
Web Pages and Web Services Professional Skills Development 7-13
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Working with the DataGrid Control
6. Click the Format node to define column widths and apply any custom
formatting to the grid, as shown in Figure 11. Here, we’ve set the
horizontal alignment for the Unit Price column to be right-aligned. (The
default for all columns is left-aligned.)
Figure 11. Specifying custom formatting.
7-14 Web Pages and Web Services Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Setting Up the DataGrid
7. If you select the Columns node within the Objects tree, you can set the
width for each column. Figure 12 shows formatting the ProductName
column as a percent, taking up 70 percent of the DataGrid. This leaves 30
percent to divide among the ID, Unit Price, and Units in Stock columns.
(Using percent values for the widths keeps the column widths in
proportion when users resize the page.)
Figure 12. Configuring each column as a percent of the whole.
Web Pages and Web Services Professional Skills Development 7-15
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Working with the DataGrid Control
8. Click Borders to specify the border color and width, as shown in Figure
13. Click OK when you’re finished.
Figure 13. Configuring the borders for the DataGrid.
Behind the Scenes
See Webform1.aspx The nice thing about the Property Builder is that it generates all the HTML
necessary to display the DataGrid properlyyou don’t need to generate it
yourself. Click the HTML tab to view the generated HTML, and you’ll see the
HTML for the page, including the description of the DataGrid control. We’ve
reformatted the HTML for the DataGrid as follows:
7-16 Web Pages and Web Services Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Setting Up the DataGrid
Display the DataGrid in Browser View
See Although you’ve been able to get this far without writing any code at all, you’ll
Webform1.aspx.vb need to write some in order to display the DataGrid in Browse view. Although
the Web form designer allows you to create controls and set their properties, it
doesn’t generate the code to initialize and run them. The following procedure
in the page’s Load event uses the IsPostBack property to see if the page is
being loaded for the first time. If so, the code loads the data into the DataSet,
calling the Fill method of the DataAdapter. Next, the code calls the DataBind
method of the DataGrid, causing it to bind to the data source, and render the
data display.
Web Pages and Web Services Professional Skills Development 7-17
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Working with the DataGrid Control
Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
'Runs first time page loads
If Not Page.IsPostBack Then
'Load the data
SqlDataAdapter1.Fill(Dataset1)
'Bind the data to the grid
DataGrid1.DataBind()
End If
End Sub
To test the DataGrid, select the page in the Solution Explorer. Right-click and
choose Build and Browse from the menu. This loads it into the browser, as
shown in Figure 14.
Figure 14. Building and displaying the DataGrid.
The DataGrid doesn’t do much at this point except display a list of products.
The following sections explain how to implement additional features available
in the DataGrid control.
7-18 Web Pages and Web Services Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Using Advanced DataGrid Features
Using Advanced DataGrid Features
See the The DataGrid control has many more built-in features than the simple ones
DataGridComplete you’ve seen so far. The DataGrid control provides many rich server-side
solution capabilities that make it an excellent choice for interacting with data. In
addition to simply displaying data in a grid, the DataGrid possesses the
following capabilities:
• Supports paging through the data displayed in the control, moving
forward, backward, or by page number.
• Displays active hyperlinks in DataGrid columns.
• Automatically displays data in editable controls at run time.
• Adds Select, Edit, Update, and Cancel buttons to the DataGrid when
data is being edited.
Figure 15 displays the completed DataGrid control with editing capabilities
and with paging, which is displayed by page numbers in the DataGrid’s header
section. In addition, each product item has a hypertext link to another page that
displays more information about each product.
Figure 15. The DataGrid control with editing and paging capabilities.
Web Pages and Web Services Professional Skills Development 7-19
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Working with the DataGrid Control
Clicking on one of the numbered page buttons in the header or footer sections
displays the ten items specified for that page, as shown in Figure 16, which
displays the items on page 6.
Figure 16. You can scroll to a numbered page.
If you press the Select button, the display changes, as shown in Figure 17
where Sasquatch Ale is selected.
Figure 17. The selected item is formatted differently than the surrounding items.
7-20 Web Pages and Web Services Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Using Advanced DataGrid Features
Clicking on the Edit button for a selected item displays additional buttons for
Update and Cancel operations and displays the Unit Price and Units in Stock
fields in editable controls, as shown in Figure 18.
Figure 18. Editing data in the DataGrid.
The following sections show you how to set up the DataGrid to implement
these features.
Data Binding
In the first section of this chapter you learned how to use the SqlConnection,
SqlDataAdapter and DataSet design-time controls to bind data to the DataGrid.
This section takes a different approach by performing all the data binding in
code. In this example, all the data binding will be done by hand, using code to
create the various objects.
In this example, the code uses Session variables to store session state from one
instance of the page to another. It maintains three Session variables:
• DataView: Maintains the data retrieved from SQL Server. Because
this is a DataView (basically, a sortable, filterable “wrapper” around a
DataSet), you can use this object to sort the data in the DataGrid.
• Sort: Maintains the current sort expression for the data in the
DataView.
Web Pages and Web Services Professional Skills Development 7-21
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Working with the DataGrid Control
• SortDirection: Maintains the current sort direction (“ASC” or
“DESC”) so that the code can toggle the sort direction if the current
sort expression is the same as the requested new one.
The code loads a DataSet with data from a table, then stores the DefaultView
property of the loaded DataTable into a Session variable—that way, the code
needn’t reload the data next time ASP.NET needs to render the page. In
addition, the page tracks the current sorting column and order of the grid so
that it can reverse the sort if necessary.
TIP: If you want to sort or filter the data in a DataSet, you must create a DataView
object, which “wraps” a DataSet object and provides these functionalities. In
this example, we’ll use a DataView to enable sorting in the grid.
See The DataFill function takes in a sort expression (a column name, usually),
DataGrid.aspx.vb creates a DataView containing the loaded data, and stores the DataView in a
Session variable. In addition, the code calls the HandleSort procedure, which
sorts the data in the DataView.
Private Sub DataFill( _
ByVal SortExpression As String)
Dim da As SqlDataAdapter
Dim ds As DataSet
Dim strSQL As String
Dim strCnn As String
strSQL = "SELECT ProductID, ProductName, " & _
"UnitPrice, UnitsInStock FROM Products"
strCnn = Constants.ConnectionString
da = New SqlDataAdapter(strSQL, strCnn)
ds = New DataSet()
da.Fill(ds, "ProductInfo")
Session("DataView") = _
ds.Tables("ProductInfo").DefaultView()
HandleSort(SortExpression)
End Sub
7-22 Web Pages and Web Services Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Using Advanced DataGrid Features
TIP: The DataFill procedure uses the SQLConnectionString property of the
Constants class to retrieve the correct connection string. Because multiple
pages in this project use the same connection information, it makes sense to
place this information as a Shared ReadOnly variable in the Constants class.
The Shared keyword enables you to use the SQLConnectionString value
without ever instantiating a Constants object. The ReadOnly keyword
prevents changing the value from within the application. Why not just make
this a constant? Constants can’t use the Shared keyword, so a read-only
variable meets the need here.
The HandleSort procedure does the work of determining whether the sort
expression has changed since the last time anyone attempted to sort the data. If
so, it sorts the data on the new expression, ascending. If not, it reverses the sort
on the currently selected sort column:
Public Sub HandleSort(ByVal SortExpression As String)
Dim strDir As String
Dim dv As DataView
If SortExpression = String.Empty Then
SortExpression = "ProductName"
strDir = "ASC"
End If
Web Pages and Web Services Professional Skills Development 7-23
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Working with the DataGrid Control
' Is the current SortExpression the same
' as the last time? If so, alter the
' direction.
If SortExpression = CStr(Session("Sort")) Then
' Was it sorted ascending or descending
' last time? Session("SortDirection") will
' tell you.
If CStr(Session("SortDirection")) = "ASC" Then
strDir = "DESC"
Else
strDir = "ASC"
End If
Else
strDir = "ASC"
End If
dv = CType(Session("DataView"), DataView)
dv.Sort = SortExpression & " " & strDir
Session("Sort") = SortExpression
Session("SortDirection") = strDir
End Sub
You’ll see how you can call the HandleSort procedure directly later in this
chapter.
The Page_Load event executes the DataFill procedure to load the data, and
then calls the GridLoad procedure to bind the data to the DataGrid:
Private Sub Page_Load( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
'Put user code to initialize the page here
If Not Page.IsPostBack Then
DataFill("ProductName")
GridLoad()
End If
End Sub
7-24 Web Pages and Web Services Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Using Advanced DataGrid Features
Private Sub GridLoad()
grdProducts.DataSource = Session("DataView")
grdProducts.DataBind()
End Sub
As you’ve already seen, the GridLoad procedure sets the DataSource property
of the DataGrid (this time, the grid is bound to the saved Session variable
named DataView, which contains a DataView object). Then it calls the
DataBind method of the grid, which causes the DataGrid control to display the
data.
Web Pages and Web Services Professional Skills Development 7-25
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Working with the DataGrid Control
Adding Advanced Features
Earlier in this chapter you learned how to set up the DataGrid and configure
columns using the Property Builder. Just as you saw earlier, the grid in this
example has four bound columns. In addition, the grid also contains some
extra columns with links. How did those get there?
TIP: You can mark columns as read-only, so that later, when you start editing the
columns, specific columns can be left out of the edit mode. In this example,
the ProductID field was marked read-only, and the Product Name field, by
virtue of its being a hyperlink column, is automatically read-only.
Adding Button Columns
To add button columns to the DataGrid, click the Columns button in the
Property Builder, and expand the Button Column node under Available
columns. In this example, we’ve added the Select, Delete, and Edit, Update,
Cancel items to the Selected columns list, as shown in Figure 19.
Figure 19. Adding Button Column items to the DataGrid.
7-26 Web Pages and Web Services Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Adding Advanced Features
Later in the chapter you’ll learn how to write the code to make these buttons
work. Without code, nothing happens when you click the buttons.
Selecting Rows
When you add a Select button column and add a format for Selected Items, a
SelectedItemStyle element is added to the HTML:
When a user clicks the row, the formatting for the selected row changes.
Figure 20 shows the SelectedItemStyle in the Property sheet.
Figure 20. Adding formatting for a selected item.
Web Pages and Web Services Professional Skills Development 7-27
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Working with the DataGrid Control
TIP: The Select button is the only button column that doesn’t require any extra
code. The link itself causes the grid to change the formatting for the selected
row.
Adding a Hyperlink Column
You can use the Property Builder to add a Hyperlink column. You then specify
the following properties:
• Text Field: Field to be displayed in the cell.
• URL Field: Field to be included as part of the URL.
• URL Format String: Content of the link, perhaps specifying a
placeholder for the field specified in the URL Field property.
To add a Hyperlink column, move Hyperlink Column from Available
columns to Selected columns, as shown in Figure 21. ProductName will be
the display value, and the hyperlink will load ProductDetail.aspx for the
selected product. In this case:
• Text field contains ProductName (the field to be displayed in the grid).
• URL field contains ProductID (the field that will be included as part of
the URL).
• URL format string contains the name of the page to be opened,
including a placeholder for the value in the URL field. In this example,
the ProductDetail.aspx page will be opened based on the ProductID
parameter. Using {0} for the parameter in the URL format string will
substitute the selected ProductID at run time and open
ProductDetail.aspx with only the selected product details displayed.
7-28 Web Pages and Web Services Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Adding Advanced Features
Figure 21. Adding a Hyperlink Column for the ProductName column.
What happens when you click on a link in the grid? When you do that, you’ll
navigate to ProductDetail.aspx, as specified in your URL format string (see
Figure 21). In addition, the grid will append a parameter that includes the ID
you’ve selected. For example, if you’ve selected item 12, the URL looks like
this:
ProductDetail.aspx?ID=12
That’s what the replaceable parameter in the URL format string does for you.
What happens, then, in ProductDetail.aspx? There, code called from the
Page_Load procedure retrieves the parameter, using the Request.QueryString
property:
strSQL = "SELECT ProductID, ProductName, " & _
"UnitPrice, UnitsInStock, UnitsOnOrder, " & _
"ReorderLevel, Discontinued FROM Products " & _
"WHERE ProductID = " & Request.QueryString("ID")
Then, once the page has built the appropriate SQL string, it fills a DataReader
object with the correct set of data and displays that data on the page. Here’s the
whole DataFill procedure, called from the Page_Load event handler:
Web Pages and Web Services Professional Skills Development 7-29
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Working with the DataGrid Control
Private Sub DataFill()
Dim cmd As SqlCommand
Dim strSQL As String
Dim strCnn As String
Dim cnn As SqlConnection
strSQL = "SELECT ProductID, ProductName, " & _
"UnitPrice, UnitsInStock, UnitsOnOrder, " & _
"ReorderLevel, Discontinued FROM Products " & _
"WHERE ProductID = " & Request.QueryString("ID")
strCnn = Constants.ConnectionString
cnn = New SqlConnection(strCnn)
cmd = New SqlCommand(strSQL, cnn)
cnn.Open()
dr = cmd.ExecuteReader( _
CommandBehavior.SingleRow Or _
CommandBehavior.CloseConnection)
' There should only be one row, right?!
' But if there isn't a row, this loop will drop out
' immediately.
Do While dr.Read()
Me.txtProductID.Text = dr("ProductID").ToString
Me.txtProductName.Text = dr("ProductName").ToString
Me.txtReorderLevel.Text = dr("ReorderLevel").ToString
Me.txtUnitPrice.Text = dr("UnitPrice").ToString
Me.txtUnitsInStock.Text = dr("UnitsInStock").ToString
Me.txtUnitsOnOrder.Text = dr("UnitsOnOrder").ToString
Me.chkDiscontinued.Checked = _
CType(dr("Discontinued"), Boolean)
Loop
dr.Close()
dr = Nothing
7-30 Web Pages and Web Services Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Adding Advanced Features
cmd.Dispose()
cmd = Nothing
cnn.Dispose()
cnn = Nothing
End Sub
Web Pages and Web Services Professional Skills Development 7-31
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Working with the DataGrid Control
Optimizing the SqlDataReader
The ADO.NET designers thought about how people would be using the product, and
the ProductDetail.aspx example shows a need that they obviously considered. This
page requires that the data provider return only a single row. A smart provider would
optimize for this case if it had that information. To make this possible, you can pass
CommandBehavior.SingleRow (a member of the CommandBehavior enumeration,
which also includes the CloseConnection value), indicating to the provider that you
only need one row. Although it’s not required, the data provider may take this
information into account, providing optimized performance. For more information, see
the CommandBehavior online help topic.
Setting Up Paging
The first step to setting up paging is to configure it in the Property Builder by
clicking the Paging button. Figure 22 shows setting the Allow paging property
to True and the Page size property to the number of rows you want displayed
in the DataGrid (the default value is 10). The Mode drop-down list provides
two choices for navigation buttonsNext, Previous, and Page numbers
buttons. (We’ve selected Page numbers, in this example.) In this case, a
maximum of ten numeric buttons representing the page numbers will be
displayed in the header section of the DataGrid.
7-32 Web Pages and Web Services Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Adding Advanced Features
Figure 22. Configuring paging for the DataGrid.
In order to react to clicking on a page number (or on a Next/Previous button, if
you’ve selected that option), you need to add code to handle the grid’s
PageIndexChanged event. In the sample page, you’ll find this code:
Private Sub grdProducts_PageIndexChanged( _
ByVal source As Object, _
ByVal e As System.Web.UI.WebControls. _
DataGridPageChangedEventArgs) _
Handles grdProducts.PageIndexChanged
grdProducts.CurrentPageIndex = e.NewPageIndex
GridLoad()
End Sub
The DataGridPageChangedEventArgs object passed as the second parameter
to the event handler, which provides a NewPageIndex property that you can
place into the grid’s CurrentPageIndex property. Once you’ve done that, you
must reload the grid with data, and the selected page will display.
Sorting Rows
When you configure each column in the Property Builder, you set a
SortExpression property for each column. When the AllowSorting property is
set to True, you’ll see a link associated with each column heading in the grid.
If a user clicks on one of those links, the grid raises its SortCommand event,
and you can write code to react to that event. The
DataGridSortCommandEventArgs object sent as the second parameter to the
event procedure provides you with the sort expression. It’s up to you to take
that expression, sort the underlying data, and rebind the grid.
The HandleSort procedure that you saw earlier takes the sort expression and
refills the Session variable containing the sorted DataView object. The
GridLoad procedure rebinds the grid to that saved DataView object:
Private Sub grdProducts_SortCommand( _
ByVal source As Object, _
ByVal e As System.Web.UI.WebControls. _
Web Pages and Web Services Professional Skills Development 7-33
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Working with the DataGrid Control
DataGridSortCommandEventArgs) _
Handles grdProducts.SortCommand
HandleSort(e.SortExpression)
GridLoad()
End Sub
Editing Rows
Earlier in this section you saw how to add Edit, Cancel, and Update button
columns to the DataGrid. Clicking on the Edit button places the grid in a
special mode in which any field that hasn’t been marked as read-only (you
control the fields in the Property Builder) is replaced with a text box for
editing. In order for editing to begin, however, you must write code that reacts
to the control’s EditCommand event. Essentially, this event gives you a
chance to indicate to the grid which row should be edited.
Once in this mode, the grid replaces the Edit button with Cancel and Update
buttons. At this point, you can enter text into the text boxes, and when you
click either the Cancel or Update buttons, the grid raises the associated event
(CancelCommand or UpdateCommand). You must write code to react to these
events, in order to instruct the underlying data source how to manage the data.
In this section, you’ll see how to handle the EditCommand, UpdateCommand,
and CancelCommand events of the DataGrid control.
NOTE To keep this section as simple as possible, we don’t discuss
writing the data back out to its data source. That is, all changes to
data will only modify the in-memory DataSet. If you want to save
the cached data back to the original data source, you’ll need to
modify the code to use the techniques discussed in the chapters on
ADO.NET.
Handling the EditCommand Event
In this event handler, you must indicate to the grid which row it should edit. To
do that, use the ItemIndex property of the Item property of the
DataGridCommandEventArgs object that is passed to the event handler. The
Item property of this object represents the selected item in the grid—it has
many other properties, as you’ll see in later sections, including a Cells
collection corresponding to the cells in the row of the table that contains the
grid’s data on the page.
7-34 Web Pages and Web Services Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Adding Advanced Features
In general, you’ll assign the ItemIndex property of the event parameter to the
EditItemIndex property of the grid, indicating which row you want edited. As
with every other event, you must rebind the grid once you’re done so that it
can display the correct data.
Private Sub grdProducts_EditCommand( _
ByVal source As Object, _
ByVal e As System.Web.UI.WebControls. _
DataGridCommandEventArgs) _
Handles grdProducts.EditCommand
grdProducts.EditItemIndex = e.Item.ItemIndex
GridLoad()
End Sub
Handling the UpdateCommand Event
Handling the UpdateCommand event is tricky. Here, you must find the correct
row in the underlying DataSet, retrieve the data from the grid, modify the data
in the DataSet, and then save the data. (Remember, you’re not saving the data
back to the original data source—you’re simply writing it back to the DataSet.
If you want to write it back to the SQL Server database, that will take a little
extra effort.)
The UpdateCommand event handler (grdProducts_UpdateCommand) is
somewhat complex, and takes these actions:
• Declares the necessary variables for the rest of the procedure:
Private Sub grdProducts_UpdateCommand( _
ByVal source As Object, _
ByVal e As _
System.Web.UI.WebControls.DataGridCommandEventArgs) _
Handles grdProducts.UpdateCommand
' Write ADO.NET code to update the data here.
Dim unitPrice As Decimal
Dim unitsInStock As Decimal
Dim dv As DataView
Dim txt As TextBox
Web Pages and Web Services Professional Skills Development 7-35
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Working with the DataGrid Control
• Retrieves the text of the modified fields. To do this, the code uses
the Cells property of the Item passed as a property of the second
parameter to the event procedure. The Item represents a row of the
grid, which is itself a standard HTML Table row. ASP.NET wraps an
object model around the row, providing a Cells collection in which
each item represents one column within the row. Each Cell object
contains a collection of Control objects, and because you know that
each cell here only contains a single control, you can refer to the
particular control you need as Item.Cells(n).Controls(0), where n
represents the column of interest.
' WARNING! The column numbers from the
' grid are hard-coded in this procedure.
' If you modify the grid, make sure you modify
' this procedure, as well!
' Retrieve the changed data.
txt = CType(e.Item.Cells(4).Controls(0), TextBox)
unitPrice = CType(txt.Text, Decimal)
txt = CType(e.Item.Cells(5).Controls(0), TextBox)
unitsInStock = CType(txt.Text, Decimal)
TIP: Option String requires that all type conversions be explicit, and the previous
code fragment needed to convert objects of type Control into TextBox
objects. To do that, the code uses the CType function to perform the
conversion. Then, each fragment needs to convert a text value (from the
associated text box) into a Decimal value. Again, the CType function does the
work.
• Retrieves the stored DataView and filters it. The procedure retrieves
the Session variable containing the DataView object, and sets its
RowFilter property. After filtering the data, there should be at least
one row in the DataView. (Actually, there should be exactly one row,
but it never hurts to be a little lenient.)
' Retrieve the stored dataview, and filter it.
dv = CType(Session("DataView"), DataView)
dv.RowFilter = "ProductID = " & e.Item.Cells(2).Text
7-36 Web Pages and Web Services Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Adding Advanced Features
• Edits the row in the DataView. After checking to ensure that there’s
at least one row in the DataView, the code uses the 0th row (dv(0)) and
performs the edit.
If dv.Count > 0 Then
With dv(0)
.Item("UnitPrice") = unitPrice
.Item("UnitsInStock") = unitsInStock
End With
End If
• Releases the filter, clears edit mode, and rebinds the grid. The code
sets the RowFilter property of the DataView back to an empty string,
effectively removing the filter. Next, it sets the EditItemIndex property
of the grid to -1, indicating that no row should be in edit mode.
Finally, the code calls the GridLoad procedure once more, forcing a
reload and rebind of the data in the grid.
' Note that we're not saving changes back to the real
' data. You learn how to do that later.
dv.RowFilter = String.Empty
grdProducts.EditItemIndex = -1
GridLoad()
End Sub
Here’s the entire procedure, in one place:
Private Sub grdProducts_UpdateCommand( _
ByVal source As Object, _
ByVal e As _
System.Web.UI.WebControls.DataGridCommandEventArgs) _
Handles grdProducts.UpdateCommand
' Write ADO.NET code to update the data here.
Dim unitPrice As Decimal
Dim unitsInStock As Decimal
Dim dv As DataView
Dim txt As TextBox
Web Pages and Web Services Professional Skills Development 7-37
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Working with the DataGrid Control
' WARNING! The column numbers from the
' grid are hard-coded in this procedure.
' If you modify the grid, make sure you modify
' this procedure, as well!
' Retrieve the changed data.
txt = CType(e.Item.Cells(4).Controls(0), TextBox)
unitPrice = CType(txt.Text, Decimal)
txt = CType(e.Item.Cells(5).Controls(0), TextBox)
unitsInStock = CType(txt.Text, Decimal)
' Retrieve the stored dataview, and filter it.
dv = CType(Session("DataView"), DataView)
dv.RowFilter = "ProductID = " & e.Item.Cells(2).Text
If dv.Count > 0 Then
With dv(0)
.Item("UnitPrice") = unitPrice
.Item("UnitsInStock") = unitsInStock
End With
End If
' Note that we're not saving changes back to the real
' data. You learn how to do that later.
dv.RowFilter = String.Empty
grdProducts.EditItemIndex = -1
GridLoad()
End Sub
Handling the CancelCommand Event
The CancelCommand event is easy to handle: all you have to do is indicate
that no row is in edit mode, then reload the grid. The DataGrid.aspx sample
page uses this code to do the job:
7-38 Web Pages and Web Services Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Adding Advanced Features
Private Sub grdProducts_CancelCommand( _
ByVal source As Object, _
ByVal e As
System.Web.UI.WebControls.DataGridCommandEventArgs) _
Handles grdProducts.CancelCommand
grdProducts.EditItemIndex = -1
GridLoad()
End Sub
Handling the DeleteCommand Event
When you click the Delete button on a DataGrid row, you trigger the control’s
DeleteCommand event. The code the example uses here is very similar to the
EditCommand event procedure, but simpler. In this case, there’s no need to
find the data to be saved—the code simply filters for the one row to be deleted
and does the work.
TIP: As you read this code, remember that we’ve hard-coded the index of the
particular cell containing the ProductID value to be deleted. If you don’t want
to do this, you can use the FindControl method of the Item object instead,
supplying the ID of the control you need to find. That seemed like overkill for
this example, but it’s worth investigating if you don’t care to hard-code the
indexes, as we’ve done here.
The DeleteCommand event handler looks like this, with the important code
marked in bold:
Private Sub grdProducts_DeleteCommand( _
ByVal source As Object, _
ByVal e As System.Web.UI.WebControls. _
DataGridCommandEventArgs) _
Handles grdProducts.DeleteCommand
' Retrieve the stored dataview, and filter it.
Dim dv As DataView
dv = CType(Session("DataView"), DataView)
dv.RowFilter = "ProductID = " & e.Item.Cells(3).Text
Web Pages and Web Services Professional Skills Development 7-39
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Working with the DataGrid Control
If dv.Count > 0 Then
dv(0).Delete()
End If
dv.RowFilter = String.Empty
grdProducts.EditItemIndex = -1
GridLoad()
End Sub
7-40 Web Pages and Web Services Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Adding Advanced Features
Summary
• The DataGrid control allows you to display data in a grid layout.
• Unlike the Repeater and DataList, the DataGrid does not require a
template, although they are supported.
• You can configure SQL Server data access by using a SqlConnection
control, a SqlDataAdapter control, and a DataSet control. Or, you can
write all the code yourself.
• You can use AutoFormat to quickly apply formatting to the DataGrid.
• The Property Builder allows you to set properties for the control in
general, for individual columns and sections, for paging, and for
borders.
• The Property Builder also allows you to add button columns to the
DataGrid for use when editing data.
• Data displayed in a Hyperlink column can be configured so that
clicking on the item loads a related page.
• Paging can be configured in the Property Builder with either a page
number to jump to a page of data or a set of Next-Previous buttons to
navigate to the next or previous pages.
• Setting a Sort Expression for a column in the property builder allows
you to write code in the SortCommand event to sort the data and
reload the grid.
• The Item.ItemIndex property is used to locate a row of data in order to
edit it.
Web Pages and Web Services Professional Skills Development 7-41
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Working with the DataGrid Control
(Review questions and answers on the following pages.)
7-42 Web Pages and Web Services Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Adding Advanced Features
Questions
1. Does the DataGrid support snaking column layout?
2. Which tool allows you to configure paging and sorting for the DataGrid?
3. What are the two ways to configure navigation when paging in the
DataGrid?
4. What do you need to set on a column in the Property Builder to enable
sorting in a DataGrid?
Web Pages and Web Services Professional Skills Development 7-43
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Working with the DataGrid Control
Answers
1. Does the DataGrid support snaking column layout?
No, it only supports a tabular layout.
2. Which tool allows you to configure paging and sorting for the DataGrid?
The Property Builder
3. What are the two ways to configure navigation when paging in the
DataGrid?
By displaying a page number, or by displaying Next-Previous
buttons.
4. What do you need to set on a column in the Property Builder to enable
sorting in a DataGrid?
A SortExpression
7-44 Web Pages and Web Services Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Adding Advanced Features
Lab 7:
Working with the
DataGrid Control
TIP: Because this lab includes code that you must type in, we’ve tried to make it
simpler for you. You’ll find all the code in DataGrid.txt in the same
directory as the sample project. To avoid typing the code, you can copy/paste
it from the text file instead.
Web Pages and Web Services Professional Skills Development 7-45
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Lab 7:
Working with the DataGrid Control
Lab 7 Overview
In this lab, you’ll fill a DataGrid control with information about the Categories
available in the Northwind sample database. Although you could write all the
code yourself, creating the various ADO.NET objects, in this lab you’ll use the
user-interface tools for creating Connection and DataAdapter objects. You’ll
also format the grid, using the AutoFormat feature and the Property Builder
dialog box. Finally, you’ll add paging and hyperlinks to the DataGrid control.
To complete this lab, you’ll need to work through three exercises:
• Display Data in a DataGrid Control
• Format the DataGrid Control
• Add Hyperlinks and Paging
Each exercise includes an “Objective” section that describes the purpose of the
exercise. You are encouraged to try to complete the exercise from the
information given in the Objective section. If you require more information to
complete the exercise, the Objective section is followed by detailed step-by-
step instructions.
7-46 Web Pages and Web Services Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Display Data in a DataGrid Control
Display Data in a DataGrid Control
Objective
A DataGrid control generally requires a data source in order to display useful
information. You can either write all the code yourself, or you can allow the
tools provided by Visual Studio .NET to do some of that work for you. In this
exercise, create SqlConnection, SqlDataAdapter, and DataSet objects using the
Visual Studio .NET data tools. Retrieve CategoryId, CategoryName, and
Description fields from the Categories table within the SQL Server sample
database, Northwind. Then, write the code that fills the DataSet and loads the
data into the grid as the page loads.
Things to Consider
• You’ll only want to run the code that loads the grid the first time the
page loads, so check for the value of the Page.IsPostback property in
your code.
• You must both fill the DataSet, and call the DataBind method of the
DataGrid control, in order to display the data.
Step-by-Step Instructions
1. Open the DataGridLab.sln project in Visual Studio .NET.
2. In the Solution Explorer window, double-click on the WebForm1.aspx
page to load the page in the Designer window.
3. Use the View|Toolbox menu item to ensure that the Toolbox window is
visible, and choose the Data tab on the Toolbox.
4. Double-click on the SqlConnection icon in the Toolbox to add an object
named SqlConnection1 to the page designer’s tray area.
5. Select the SqlConnection1 object. In the Properties window, find the
ConnectionString property, click in the drop-down arrow to the right of
the property, and select from the drop-down list.
6. Supply values in the Data Link Properties dialog box, as shown in Figure
23.
Web Pages and Web Services Professional Skills Development 7-47
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.Lab 7:
Working with the DataGrid Control
NOTE This lab, as all the others, assumes that you have a local
installation of SQL Server 2000 or higher, and that you can log in
as sa with a blank password. If that isn’t the case, you’ll need to
adjust the values in this dialog box accordingly.
Figure 23. The completed Data Link Properties dialog box should look like this.
7. In the Toolbox window, double-click on the SqlDataAdapter icon to add
an object named SqlDataAdapter1 to the page’s tray area.
8. Right-click on SqlDataAdapter1 and select Configure Data Adapter
from the context menu. This brings up the Data Adapter Configuration
Wizard. Click Next to bypass the Welcome page of the Wizard.
9. On the Choose Your Data Connection page, select the default connection
(the one you just added), and click Next.
10. On the Choose a Query Type page, accept the default Use SQL
statements option, and click Next.
7-48 Web Pages and Web Services Professional Skills Development
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.You can also read