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

Microsoft ADO .NET 4 Step by Step - p 10 potx

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 (588.8 KB, 10 trang )

66 Microsoft ADO.NET 4 Step by Step
Selecting and Sorting
DataRow
Objects: Visual Basic
Note This exercise uses the “Chapter 4 VB” sample project and continues the previous exercise
in this chapter.
1. Open the source code view for the TableExaminer form. Locate the ActCriteria_Click
event handler. This routine collects user-supplied selection and sorting expressions;
then uses them to obtain a set of DataRow instances from a DataTable. Most of the
code exists to ensure that the user provides valid expressions.
2. Locate the Try Catch statement just after the “Apply the filter and sorting list” com-
ment. In the Try block, add the following statement:
results = workTable.Select(CriteriaFilter.Text, CriteriaSorting.Text)
This line performs the actual row selection, returning the optionally sorted DataRow
instances or an empty array when the selection expression doesn’t match any of the
table’s rows.
3. Run the program. On the Lookup By Criteria tab, provide expressions that will return
a list of students with improving grades, sorted by name. Enter ScoreTrimester3 >
ScoreTrimester1 OR ScoreTrimester3 > ScoreTrimester2 in the Filter Criteria field,
and StudentName in the Sorting List field. Click Lookup. The matching rows appear in
a separate window.
Chapter 4 Accessing the Right Data Values 67
Performing Case-Sensitive Lookups
The Select method ignores character casing by default when comparing string values. For
instance, the following expression will match joe, Joe, JOE, or any other mixed-case variation
on the name:
FirstName = 'joe'
To enforce case-sensitive matches on all searches instead, set the table’s CaseSensitive
property.
C#
someTable.CaseSensitive = true;


Visual Basic
someTable.CaseSensitive = True
Using Expression Columns
In Chapter 2, “Building Tables of Data,” you learned how to add columns to a table that
would each hold data values of a specific type. These static columns define the core data
within a table. The DataTable class also supports expression columns, fields that expose a cal-
culated result based on the data in other row columns. For instance, if your table of orders
includes a Subtotal column and a Tax column, you could add an expression column named
Total that calculated the sum of Subtotal and Tax.
68 Microsoft ADO.NET 4 Step by Step
To add an expression column to a table, create a standard DataColumn object, fill in its
ColumnName and DataType properties, and then assign a string expression that performs the
custom calculation to the Expression property.
C#
// Syntax using a DataColumn object.
DataColumn orderTotal = new DataColumn();
orderTotal.ColumnName = "Total";
orderTotal.DataType = typeof(decimal);
orderTotal.Expression = "Subtotal + ISNULL(Tax, 0)";
someTable.Columns.Add(orderTotal);

// Syntax using Add arguments only.
someTable.Columns.Add("Total", typeof(decimal),
"Subtotal + ISNULL(Tax, 0)");
Visual Basic
' Syntax using a DataColumn object.
Dim orderTotal As New DataColumn
orderTotal.ColumnName = "Total"
orderTotal.DataType = GetType(Decimal)
orderTotal.Expression = "Subtotal + ISNULL(Tax, 0)"

someTable.Columns.Add(orderTotal)

' Syntax using Add arguments only.
someTable.Columns.Add("Total", GetType(Decimal),
"Subtotal + ISNULL(Tax, 0)")
The expression field uses the same elements from Table 4-1 that you used with the
DataTable.Select method. To view the full documentation for this expression, access the
Visual Studio online help entry for “DataColumn.Expression Property.”
Note
The documentation for the Ex pression property discusses “aggregate functions.” These are
covered in Chapter 6.
After being added to your table, you can query expression columns in Select statements or
examine them with standard ADO.NET code just like static columns. Expression columns are
not calculated until you attempt to access them. If there is anything wrong with the expres-
sion, such as including references to non-existent columns, the code accessing the column
will throw an exception.
Chapter 4 Accessing the Right Data Values 69
Adding Expression Columns to a
DataTable
: C#
Note This exercise uses the “Chapter 4 CSharp” sample project and continues the previous exer-
cise in this chapter.
1. Open the source code view for the TableExaminer form. Locate the ActExpression_Click
event handler. This routine defines up to three expression columns based on column
names, data types, and calculation expressions supplied by the user. It then adds these
columns to the application’s sample DataTable. Most of the code exists to ensure that
the user provides valid column definitions.
2. Locate the try catch statement just after the “Add the expression column” comment. In
the try block, add the following statement:
workTable.Columns.Add(nameField.Text.Trim(),

Type.GetType("System." + typeField.SelectedItem.ToString()),
expressionField.Text);
This code adds the expression columns to the sample table, passing the column name,
the data type from the System namespace, and the field expression.
3. Run the program. On the Add Expression Columns tab, fill in the Name, Type, and
Expression fields with the desired custom columns. To create a column that calcu-
lates the average annual score for each student, in the first row of fields, set Name
to YearAverage, select Decimal in the Type field, and enter (ScoreTrimester1 +
ScoreTrimester2 + ScoreTrimester3) / 3 in the Expression field.
4. Expression columns can reference other expression columns. Create a column that
calculates a letter grade for the YearAverage column. In the second row of fields,
enter LetterGrade in the Name field, select String in the Type field, and enter
IIF(YearAverage >= 3.5, 'A', IIF(YearAverage >= 2.5, 'B', IIF(YearAverage >= 1.5, 'C',
IIF(YearAverage >= 0.5, 'D', 'F')))) in the Expression field. Click Build to see the results.
70 Microsoft ADO.NET 4 Step by Step
Adding Expression Columns to a
DataTable
: Visual Basic
Note This exercise uses the “Chapter 4 VB” sample project and continues the previous exercise
in this chapter.
1. Open the source code view for the TableExaminer form. Locate the ActExpression_Click
event handler. This routine defines up to three expression columns based on column
names, data types, and calculation expressions supplied by the user. It then adds these
columns to the application’s sample DataTable. Most of the code exists to ensure that
the user provides valid column definitions.
2. Locate the Try Catch statement just after the “Add the expression column” comment. In
the Try block, add the following statement:
workTable.Columns.Add(nameField.Text.Trim,
Type.GetType("System." & typeField.SelectedItem.ToString),
expressionField.Text)

This code adds the expression columns to the sample table, passing the column name,
the data type from the System namespace, and the field expression.
3. Run the program. On the Add Expression Columns tab, fill in the Name, Type, and
Expression fields with the desired custom columns. To create a column that calcu-
lates the average annual score for each student, in the first row of fields, set Name
to YearAverage, select Decimal in the Type field, and enter (ScoreTrimester1 +
ScoreTrimester2 + ScoreTrimester3) / 3 in the Expression field.
4. Expression columns can reference other expression columns. Create a column that
calculates a letter grade for the YearAverage column. In the second row of fields,
enter LetterGrade in the Name field, select String in the Type field, and enter
IIF(YearAverage >= 3.5, 'A', IIF(YearAverage >= 2.5, 'B', IIF(YearAverage >= 1.5,
'C', IIF(YearAverage >= 0.5, 'D', 'F')))) in the Expression field. Click Build to see the
results.
Chapter 4 Accessing the Right Data Values 71
Summary
This chapter introduced different ways to access records previously added to a DataTable
instance. The DataTable.Rows.Find method uses the table’s primary key value(s) to return a
single DataRow instance, similar to the way that .NET’s Generic.Dictionary class returns an
object based on a lookup key. The DataTable.Select method also performs a row lookup, but
uses a SQL–like Boolean expression, expanding the search criteria to all columns in the table,
not just the primary key. This method also provides a way to sort the results.
Expression columns let you add real-time calculated values to each DataRow in your table.
Like the other columns in the table, expression columns are strongly typed. Because they are
calculated only when accessed, their values refresh automatically whenever any of their de-
pendent column values change.
Chapter 4 Quick Reference
To Do This
Access a DataRow by its primary key Add DataColumn instances to a DataTable.
Add one or more of those DataColumn instances to the
table’s PrimaryKey property.

Add relevant DataRow objects to the DataTable.
Call the table’s Rows.Find method, passing it the desired
row’s primary key value(s).
Locate DataRow objects with a SQL-like query Add DataColumn instances to a DataTable.
Add relevant DataRow objects to the DataTable.
Build a query expression string (see the “DataColumn.
Expression Property” entry in online help).
Call the table’s Select method, passing it the query
expression.
Perform a case-sensitive or
case-insensitive DataRow lookup
Set the DataTable object’s CaseSensitive Boolean property.
Call Rows.Find or Select methods with string search
content.
Add calculated columns to a DataTable Add standard DataColumn instances to a DataTable.
Create a new DataColumn instance for the calculated
column.
Assign the DataColumn object’s ColumnName and
DataType fields.
Build a column expression string (see “DataColumn.
Expression Property” entry in online help).
Set the DataColumn object’s Expression property to the
expression string.
Add the DataColumn to the DataTable.

73
Chapter 5
Bringing Related Data Together
After completing this chapter, you will be able to:


Join multiple DataTable instances into a DataSet

Establish parent-child relationships between tables of data

Understand the types of table constraints available in ADO.NET

Build relationships that auto-correct linked rows when needed
The D ataTable class provides ADO.NET’s core data-management functionality. But many
of the tools that build and interact with DataTable content do so through a higher level of
abstraction: the DataSet. Instead of relying on a single table’s worth of DataRows, a DataSet
links multiple tables together, making it possible to generate data queries based on the rela-
tionships between the tables and their data.
In this chapter, the DataSet object takes center stage. You will discover how a DataSet becomes
more than the sum of its DataTable parts. By combining data tables, relationship definitions be-
tween those tables, and column-specific constraints that help ensure data integrity between
the tables, ADO.NET provides new views on data that would be complicated to achieve with
solitary data tables.
Note
The exercises in this chapter all use the same sample project, a tool that shows the related
records between two DataTable instances. Although you will be able to run the application after
each exercise, the expected results for the full application might not appear until you complete
all exercises in the chapter.
Collecting Tables into Sets
ADO.NET includes a System.Data.DataSet class that defines a collection of tables, their rela-
tionships, and related field constraints. To establish a data set in your program, create a new
DataSet object, optionally passing it a set name.
C#
DataSet someSet = new DataSet("SetName");
Visual Basic
Dim someSet As New DataSet("SetName")

74 Microsoft ADO.NET 4 Step by Step
Adding a name to a standalone DataTable instance might be inconsequential, but some
table-related features in ADO.NET do enable access to a DataTable object by its table name.
For example, the D ataSet class includes a Tables property that, as expected, holds a collection
of individual DataTable instances. You access tables within the collection either by name or
by an index number. To add a new DataTable to a DataSet, write the following:
C#
someSet.Tables.Add(someTable);
Visual Basic
someSet.Tables.Add(someTable)
You can also pass a string to the Add method, which creates a new named table object with-
out columns or rows. You can add as many data tables as you want to the Tables collection.
At this point, they are still treated as individual tables; adding them to the collection of tables
does not automatically endow them with relationship features.
Note
A DataSet can contain two tables with the same name as long as their namespace values
differ. Chapter 7, “Saving and Restoring Data,” discusses these namespaces. Also, if two tables
share a common name (and namespace) but differ in the casing of those names (“CUSTOMERS”
versus “customers”), the DataSet will treat them as distinct tables. When querying these tables,
you must provide the same casing as the original table names, or else the query will fail.
However, if a table name has no duplicate within a DataSet, its name in queries can be case-
insensitive.
The D ataSet includes some properties and methods that replicate the functionality of the
contained tables. These features share identical names with their table counterparts. When
used, these properties and methods work as if those same features had been used at the
table level in all contained tables. Some of these members that you’ve seen before include
the following:

Clear


CaseSensitive

AcceptChanges

RejectChanges

EnforceConstraints

HasErrors
Chapter 5 Bringing Related Data Together 75
Adding Tables to a
DataSet
: C#
1. Open the “Chapter 5 CSharp” project from the installed samples folder. The project in-
cludes three Windows.Forms classes: FlightInfo, FlightDetail, and LegDetail.
2. Open the source code view for the FlightInfo form. Locate the BuildSampleDataSet
function. This routine creates the main DataSet used in the application.
3. Just after the “Add the two tables to the data set” comment, add the following
statements:
result = new DataSet("FlightSample");
parentTable = BuildFlightTable();
childTable = BuildLegTable();
result.Tables.Add(parentTable);
result.Tables.Add(childTable);
These lines create two tables that share a common value: the flight ID number. In the
flight table the field is named ID, whereas it is called FlightID in the leg table. A later
example in this chapter will establish the relationship between the two tables.
Adding Tables to a
DataSet
: Visual Basic

1. Open the “Chapter 5 VB” project from the installed samples folder. The project includes
three Windows.Forms classes: FlightInfo, FlightDetail, and LegDetail.
2. Open the source code view for the FlightInfo form. Locate the BuildSampleDataSet
function. This routine creates the main DataSet used in the application.
3. Just after the “Add the two tables to the data set” comment, add the following
statements:
result = New DataSet("FlightSample")
parentTable = BuildFlightTable()
childTable = BuildLegTable()
result.Tables.Add(parentTable)
result.Tables.Add(childTable)
These lines create two tables that share a common value: the flight ID number. In the
flight table the field is named ID, whereas it is called FlightID in the leg table. A later
example in this chapter will establish the relationship between the two tables.

×