Tải bản đầy đủ (.pdf) (22 trang)

Binding Data with ADO.NET

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (560.94 KB, 22 trang )

Chapter 21
Binding Data with ADO.NET
After completing this chapter, you will be able to:

Bind data to controls in Windows Forms, WPF, and ASP.NET applications

Understand the classes and technologies that make binding possible

Create working database programs with simple drag-and-drop techniques
Data binding involves connecting display and data-entry controls with a data source in a
way that somewhat automates the data management process. Rather than writing code that
manually transfers data between, say, a DataTable instance and individual TextBox controls,
you configure the controls to understand how they should obtain data from the DataTable.
This simulated simplicity—the true complexity is hidden away inside of .NET controls and
classes—brings Rapid Application Development (RAD) features from pre-.NET versions of
Visual Basic into the .NET world.
This chapter provides brief demonstrations of using data binding in three types of .NET
applications: Windows Forms, Windows Presentation Foundation (WPF), and ASP.NET. In
each case, you’ll create a sample application with simple drag-and-drop techniques, with no
additional code added to enable data migration. A discussion of the technologies involved
follows each example.
Binding Data in Windows Forms
The Windows Forms system supports two types of binding scenarios based on the features
of individual controls: simple and complex. In simple data binding, a control hosts a single
value from a single data record, such as a TextBox that supports displaying or editing a cus-
tomer name. In this arrangement, a form typically hosts multiple controls, each of which is
bound to a specific data row field.
In complex data binding, a single control expresses a list of records, perhaps all records in
a table. The control can include features that indicate how to display the complexities of a
data row in a single control entry. The ListBox control is a typical candidate for complex data
binding.


Dwonloaded from: iDATA.ws
348
Creating Complex-Bound Applications
You’ve already seen complex data binding demonstrated throughout this book. Starting with
Chapter 4, many of the sample applications employed the DataGridView control to display
data results. Assigning a compatible array or collection to that control’s DataSource property
renders the data within the control’s visible grid.
The most interesting use of the control appeared in Chapter 11, “Making External Data Available
Locally,” where a data adapter-enabled DataTable instance was linked to the DataGridView.
DataSource property. The sample code built a data adapter link to the UnitOfMeasure table,
crafting each of the INSERT, UPDATE, and DELETE statements before making the assignment
to the grid control.
C#
UnitAdapter.Fill(UnitTable);
UnitGrid.DataSource = UnitTable;
Visual Basic
UnitAdapter.Fill(UnitTable)
UnitGrid.DataSource = UnitTable
By having an active data adapter as part of the control’s input source, changes made to
data values within the grid propagate back to the external data source, essentially creating
a miniature grid-based table editor. That sample could be shortened even more to use a
SqlCommandBuilder, freeing you from even having to craft the three SQL data manipulation
statements. But even with this change, you still need a bit of custom code to make the grid
work.
For an even simpler grid-based solution, you can build an application that supports editing
of database table values without writing a single line of code. Creating such a program in-
volves little more than dragging tables from a wizard-configured data source to the surface
of a form.
Creating a Complex Data-Bound Form
1. Create a new Windows Forms application using either Visual Basic or C#. The new proj-

ect displays a single blank form.
2. Add a data source for the table to be edited. The “Connecting to External Data” section
in Chapter 1, “Introducing ADO.NET 4,” includes step-by-step instructions for creat-
ing such a data source. Follow those instructions. When you reach the Choose Your
Dwonloaded from: iDATA.ws
Chapter 21 Binding Data with ADO.NET
349
Database Objects panel in step 14 of the instructions, select the CourseCatalog table
from the list. Type CourseDataSet in the DataSet Name field. Click Finish to add the
DataSet to the project.
3. The Data Sources panel in Visual Studio now contains a CourseDataSet tree with the
CourseCatalog table as a branch within it. Expand the CourseCatalog branch to see the
individual fields associated with the table: four text fields and two Boolean fields.
Dwonloaded from: iDATA.ws
350
Microsoft ADO.NET 4 Step by Step
4. The CourseCatalog branch is actually a drop-down list; click its name to enable the list.
Expand the list and ensure that DataGridView is selected.
5. Drag the CourseCatalog name from the Data Sources panel and drop it on the blank
form’s surface. This action adds a DataGridView control to the form with columns for
each of the table’s fields. It also adds a toolbar-style control and several non-visual con-
trols to the bottom of the design window. Resize the form and grid control as needed.
6. Run the program. When the form appears, the grid will display any records already
found in the CourseCatalog table. Note that the data is fully editable; you can add, up-
date, and delete records in the table through the form.
Dwonloaded from: iDATA.ws
Chapter 21 Binding Data with ADO.NET
351
Creating Simple-Bound Applications
The DataGridView control and the accompanying VCR-style control in the complex-bound

solution provide an editing experience reminiscent of Microsoft Access’ default table edit-
ing environment. If a grid interface doesn’t meet your data display and editing needs, Visual
Studio can generate a data-bound form that hosts each data value in a distinct control. This
method gives the form a more traditional data-editing look while still keeping the promise of
no-custom-code simplicity.
Creating a Simple Data-Bound Form
1. Create a new Windows Forms application using either Visual Basic or C#. The new proj-
ect displays a single blank form.
2. As in the prior example, use the Data Source Configuration Wizard to create a
CourseDataSet data set that contains the CourseCatalog table.
3. In the Data Sources panel, click the drop-down for the CourseCatalog table branch and
select Details from the list of choices.
Note
The field names for each table as displayed in the Data Sources panel are also drop-down
lists. These lists allow you to indicate what type of simple data-bound control will be used to dis-
play the data on the target form.
4. Drag the CourseCatalog name from the Data Sources panel and drop it on the blank
form’s surface. This action adds separate TextBox and CheckBox controls to the form for
each column in the CourseCatalog table. It also adds a toolbar-style control, and several
nonvisual controls to the bottom of the design window. Resize the form and data con-
trols as needed.
Dwonloaded from: iDATA.ws
352
Microsoft ADO.NET 4 Step by Step
5. Run the program. When the form appears, it displays one record from the
CourseCatalog table. The data is fully editable, and you can add, update, and delete re-
cords in the table through the form.
Understanding Windows Forms Data Binding
Although these simple applications work without the need for custom code, the form and its
display controls, the data set, and the nonvisual controls added to the form each include suf-

ficient code to enable source-to-user data management.
When you drag a table to the form’s surface in either the complex-style or simple-style bind-
ings, Visual Studio builds a hierarchy of classes that work together to transport data between
the database and the user. The following list identifies the members of this chain, moving
from the source-side to the form-side of the interaction.

TableAdapter As discussed in Chapter 11, a data adapter enables bidirectional move-
ment of a table’s content. Because the bound controls display data and accept updates
from the user, the adapter keeps the database and the form in sync.

TableAdapterManager This object, added to the form by Visual Studio, assists the
TableAdapter in hierarchical-data environments. The CourseCatalog examples shown
above do not include hierarchical data.
Dwonloaded from: iDATA.ws
Chapter 21 Binding Data with ADO.NET
353

DataSet This is the wizard-built DataSet instance added to the Data Sources panel.
It’s actually a strongly typed data set, which is not discussed in this book other than to
point out how the Entity Framework (EF) expands on the basic strongly typed data set
functionality.

BindingSource Although Windows Forms controls can bind directly to ADO.NET
DataTable instances, such a relationship provides only minimal functionality. The
BindingSource class enriches this relationship by adding change notifications, error
management, and consistent movement functionality between the records of a source
data table.

BindingContext The binding context doesn’t appear as one of the controls added by
Visual Studio, but it is present. It appears as a member of the form itself and exists in

parallel in each of the controls that participate in the data binding operation. A single
form (or some other equivalent data surface, such as a Panel control) can support mul-
tiple binding contexts, one for each source of incoming and outgoing data displayed
on the form. Each context is defined by its source (typically a reference to the DataSet
instance or other top-level data source) and the path within the source (for DataSet
instances, this typically refers to the table name). The BindingContext instances manage
the comings and goings of all data, keeping all controls that share a common context
in sync with each other. It ensures that controls managing the same source table don’t
point to different rows.

Form and controls The form surface and the individual data control form one end-
point of the data-binding relationship. Each control exposes a DataBindings collection
that maps bound data to specific properties of the control. For instance, in the preced-
ing simple-bound example, the incoming CourseCatalog.CourseName field is mapped
to the CourseNameTextBox control’s Text property. But data can be bound to other
properties as well. For example, you can map a control’s BackColor property to a data-
base field that tracks color values.
In addition to the grid or detail controls added to the form, dragging a data source table to
a form adds a BindingNavigator control, a “VCR” control that lets the user move between the
different rows of the table, adding and deleting rows as needed. One of the buttons on this
toolbar, the Save button (with a floppy disk image), includes some code-behind in its Click
event handler.
C#
this.Validate();
this.courseCatalogBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.courseDataSet);
Dwonloaded from: iDATA.ws
354
Microsoft ADO.NET 4 Step by Step
Visual Basic

Me.Validate()
Me.CourseCatalogBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.CourseDataSet)
This code finishes up all pending edits and saves all changes to the database, bringing every-
thing back in sync.
As convenient as these data binding examples are, it is rare that an application can meet us-
ability needs without providing additional custom code. In addition to using these simple
techniques, you can augment the generated controls and code with your own source code or
use the generated source as a basis for designing your own data-bound environments.
Binding Data in WPF
Windows Presentation Foundation (WPF) applications use an XML-based schema language
called XAML to define the user interface and behavioral aspects of an application. Visual
Studio includes support for building WPF/XAML applications, presenting a design experience
that is similar to standard Windows Forms development.
Note
An introduction to the Windows Presentation Foundation and its XML-based way of de-
scribing application elements is beyond the scope of this book.
Creating Data-Bound WPF Applications
WPF applications in Visual Studio support the same type of drag-and-drop data-bound ap-
plication building features present in Windows Forms projects, albeit with some variations.
The following examples guide you through the construction of a data-bound WPF project.
Dwonloaded from: iDATA.ws

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×