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,
Trang 1Chapter 21
Binding Data with ADO NET
After completing this chapter, you will be able to:
■ 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
Trang 2You’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
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 volves little more than dragging tables from a wizard-configured data source to the surface
in-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 ing such a data source Follow those instructions When you reach the Choose Your
Trang 3creat-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
Trang 44 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 trols to the bottom of the design window Resize the form and grid control as needed
con-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,
Trang 5up-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 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
edit-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 trols as needed
Trang 6con-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 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
bind-■
■ 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
Trang 7■ 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 incompreced-ing 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
Trang 8Windows 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 scribing application elements is beyond the scope of this book.
de-Creating Data-Bound WPF Applications
WPF applications in Visual Studio support the same type of drag-and-drop data-bound 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
Trang 9ap-Creating a Data-Bound WPF Project
1 Create a new WPF Application project using either Visual Basic or C# The new
proj-ect displays a single blank window with associated XAML content below the visual representation
2 As in the prior examples, 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
4 Drag the CourseCatalog name from the Data Sources panel and drop it on the blank
WPF window surface This action adds a grid to the form that hosts separate Label, TextBox, and CheckBox controls for each column in the CourseCatalog table.
Trang 105 Run the program When the form appears, it displays the first record from the
CourseCatalog table.
Trang 11Building the WPF project is simple using drag-and-drop techniques, but as the example ect demonstrates, it’s possible to view only the initial record in the incoming table The fol-lowing language-specific projects add navigation features.
proj-Adding Navigation to a Data-Bound WPF Window: C#
Note This exercise continues the initial WPF exercise in this section.
1 Add four Button controls from the Toolbox panel to the WPF window surface Name the
buttons ActFirst, ActPrevious, ActNext, and ActLast; set their Content property
val-ues to First, Previous, Next, and Last, respectively.
2 Double-click the ActFirst button control When the event handler appears, add the
3 Back on the window design surface, double-click the ActPrevious button control When
the event handler appears, add the following code:
// - Move to the previous record in the table
System.Windows.Data.CollectionViewSource catalogSource =
(System.Windows.Data.CollectionViewSource)
Trang 124 Back on the window design surface, double-click the ActNext button control When the
event handler appears, add the following code:
// - Move to the next record in the table
5 Back on the window design surface, double-click the ActLast button control When the
event handler appears, add the following code:
// - Move to the last record in the table
System.Windows.Data.CollectionViewSource catalogSource =
(System.Windows.Data.CollectionViewSource)
this.FindResource("courseCatalogViewSource");
catalogSource.View.MoveCurrentToLast();
6 Run the program When the form appears, it displays the first record from the
CourseCatalog table Use the new navigation buttons to move through the records in
the bound table
Adding Navigation to a Data-Bound WPF Window: Visual Basic
Note This exercise continues the initial WPF exercise in this section.
Trang 132 Double-click the ActFirst button control When the event handler appears, add the
fol-lowing code:
' - Move to the first record in the table
Dim catalogSource As System.Windows.Data.CollectionViewSource =
CType(Me.FindResource("CourseCatalogViewSource"),
System.Windows.Data.CollectionViewSource)
catalogSource.View.MoveCurrentToFirst()
3 Back on the window design surface, double-click the ActPrevious button control When
the event handler appears, add the following code:
' - Move to the previous record in the table
Dim catalogSource As System.Windows.Data.CollectionViewSource =
CType(Me.FindResource("CourseCatalogViewSource"),
System.Windows.Data.CollectionViewSource)
If (catalogSource.View.CurrentPosition > 0) Then _
catalogSource.View.MoveCurrentToPrevious()
4 Back on the window design surface, double-click the ActNext button control When the
event handler appears, add the following code:
' - Move to the next record in the table
Dim catalogSource As System.Windows.Data.CollectionViewSource =
Trang 145 Back on the window design surface, double-click the ActLast button control When the
event handler appears, add the following code:
' - Move to the last record in the table
Dim catalogSource As System.Windows.Data.CollectionViewSource =
CType(Me.FindResource("CourseCatalogViewSource"),
System.Windows.Data.CollectionViewSource)
catalogSource.View.MoveCurrentToLast()
6 Run the program When the form appears, it displays the first record from the
CourseCatalog table Use the new navigation buttons to move through the records in
the bound table
Understanding WPF Data Binding
The DataSet, TableAdapter, and TableAdapterManager instances used in the Windows Forms
bound data example earlier in this chapter also appear in the WPF example That’s because those portions are generated by the Data Source Configuration Wizard; they are not depen-dent on the type of project in which they appear In WPF, as in Windows Forms, they manage retrieving the data from the external data source and propagating any changes from the ap-plication back to the data source
The binding elements that connect the DataSet content to the on-window fields vary
sig-nificantly between WPF and Windows Forms Much of a WPF application is declared using XAML, and data bindings are no different To enable data binding, Visual Studio adds infor-
mation on the data source to the Grid control that hosts the individual data controls.