Working with Row State Information

From Chapter 6: Disconnected Data via ADO.NET and DataSets of the book Extending MFC Applications with the .NET Framework.

This article is a continuation of the previous article, "Doing Database Operations In Batches."

Searching, Sorting, and Filtering Data

So far, you've learned how to connect to a data store, retrieve the desired data, close the connection, modify the data locally (including adding, editing, and deleting records), and then update the data store at will—once again only holding the connection long enough to synchronize your in-memory representation of the data with the data store. As you'll discover in this section, the ADO.NET classes also support the ability to search, sort, and filter data once it's been retrieved. In fact, being able to perform these operations against your disconnected data without making continual round trips to the server is one of the strongest arguments for using disconnected data to begin with.

We'll begin by looking at how to search the DataTable and DataRow Collection objects using both primary keys and column data. After that, you'll see how to create DataView objects to represent different views on the same DataTable object where you can filter on both column values and row state information, which we covered in the previous section. Finally, you'll discover how to sort and search through these filtered DataView objects.

Searching DataTable and DataRowCollection Objects

There are two basic ways to search a DataTable and its internal DataRow Collection—by primary key and by column value. We'll start with the primary key search, as that technique was used in the EmployeeMaintenance demo application.

Searching on Primary Key

The DataRowCollection::Find method is used to retrieve a DataRow from a DataRowCollection by its primary key value. This method has overloaded versions that return a DataRow instance. A value of null is returned if a row containing the specified primary key value(s) cannot be located in the collection.

public: DataRow* Find(Object*);
public: DataRow* Find(Object*[]);

The first Find method enables you to specify a single primary key value, while the second enables you to specify an array of values if the primary key has more than one column. Note that passing an array whose length is greater than the number of defined primary keys columns results in an ArgumentException, where exception object's Message property will indicate both how many values were expected and how many were specified in the Find method.

Also keep in mind that in order to use the Find method with an untyped dataset, you'll need to either set the data adapter object's Missing SchemaAction property to MissingSchemaAction::AddWithKey (before the call to the adapter's Fill method) or manually set the DataTable object's Primary key property by passing it an array of DataColumn objects that correspond to the table's primary key columns. Both of these techniques are described in more detail in the section entitled "Filling in Missing Schema and Primary Key Information for Untyped Datasets."

In the following example, I'm using the Find method to locate an employee record with a primary key value of 1. As the Employees table's EmployeeID column is defined as its only primary key column, then this search is basically the equivalent of an SQL statement like SELECT * where EmployeeID = 1.

// Search for a primary key made up of a single column
// Assumes a connection to the Employees table
...

DataRow* row = employeesTable->Rows->Find(__box(1));
if (row)
{
   // Have DataRow to use
   Console::WriteLine(String::Format(S"Found record > {0} {1}",
                      row->Item[S"FirstName"],
                      row->Item[S"LastName"]));
}
else
   Console::WriteLine(S"Could not locate record");

The sample Employee table contains a record for a "Nancy Davolio" that has an EmployeeID value of 1, so her name should print out. Now let's see how to perform a Find operation with more than one primary key column. As the Employees table has only a single column defined as its primary key column, the following sample will also include code to override that fact and tell the DataTable that the FirstName and LastName columns are now the primary key columns.

/ Search for a primary key made up of multiple columns
// Assumes a connection to the Employees table/
...

// Tell the DataTable that the FirstName and LastName
// columns are now the primary key columns
employeesTable->PrimaryKey = NULL;
DataColumn* keys[] = new DataColumn*[2];
keys[0] = employeesTable->Columns->Item[S"FirstName"];
keys[1] = employeesTable->Columns->Item[S"LastName"];
employeesTable->PrimaryKey = keys;
// Build the primary key search value array
Object* search[] = new Object*[2];

search[0] = S"Nancy";
search[1] = S"Davolio";

DataRow* row = employeesTable->Rows->Find(search);
if (row)
{
   // Have DataRow to use
   Console::WriteLine(String::Format(S"Found record > {0}",
                      row->Item[S"EmployeeId"]));
}
else
   Console::WriteLine(S"Could not locate record");

In addition to the Find method, the DataRowCollection also includes a method called Contains, which allows you to perform the same exact search as the Find method, with the difference being that instead of a DataRow being returned, a Boolean value is returned indicating the success or failure of the search.

Searching (and Sorting)on Column Values

In order to search a DataTable for a given column value, you can use the DataTable::Select method and specify search criteria much like those of the SQL SELECT statement. The Select method has the following overloads.

DataRow* Select() [];
DataRow* Select(String* criteria) [];
DataRow* Select(String* criteria, String* sort) [];
DataRow* Select(String* criteria, String* sort, DataViewRowState) [];

The first (parameter-less) version of this method simply returns all rows in the DataTable object's DataRowCollection in a DataRow array sorted by primary key. If the table does not contain a primary key, then the rows are sorted in arrival sequence (the order in which they were added to the collection).

The second—and most used—version allows you to specify the search criteria. As mentioned, this criterion is much like specifying the value of an SQL SELECT statement without the SQL verbs. As with the parameter-less Select method, the resulting DataRow array is either sorted by primary key or, in the absence of a defined primary key column, arrival sequence.

The third version of the Select method enables you to specify search criteria as well as the columns to use in sorting the returned DataRow array. You can also append the standard SQL ASC and DESC to the column to indicate an ascending or descending sort, respectively.

Finally, the last Select method overload enables you to specify search criteria using the sort columns and a DataViewRowState enumeration value. In the section entitled "Working with Row State Information," you learned that the DataRow object maintains a state property indicating such things as whether or not the row has been added or changed (but not committed), deleted, or unchanged. The valid DataViewRowState enumeration values and their descriptions are listed and explained in the section entitled "Filtering on Row State Information."

Here are several examples of how to use the Select method that illustrate how robust this feature is. For example, aside from the standard comparison operators such as =, <, >, and <>, you also have the ability to use the SQL wildcards * and % with the LIKE predicate, user-defined values for comparisons on types such as dates, and special built-in functions such as SUBSTRING.

void PrintResults(DataRow* rows[])
{
   Console::WriteLine();
   String* format = S"{0,-7} {1, -10} {2}";
   Console::WriteLine(format, S"Record", S"First Name", S"Last Name");
   for (int i = 0; i < rows->Count; i++)
   {
      Console::WriteLine(format,
                         __box(i),
                         rows[i]->Item[S"FirstName"],
                         rows[i]->Item[S"LastName"]);
   }
}

void Select()
{
#pragma push_macro("new")
#undef new
   try
   {
      DataRow* rows[];
      // Search on a single column
      rows = employeesTable->Select(S"LastName = 'Archer'");
      PrintResults(rows);
      // Search on multiple columns
      rows = employeesTable->Select(S"FirstName = 'Tom' "
                                    S"AND LastName = 'Archer'");
      PrintResults(rows);
      // Search using the SQL LIKE predicate
      rows = employeesTable->Select(S"Title LIKE 'Sales*'");
      PrintResults(rows);
      // Search and Sort on two columns
      rows = employeesTable- Select(S"City = 'London'",
                                      S"LastName,FirstName");
      PrintResults(rows);
      // Search and Sort in DESCending order
      rows = employeesTable->Select(S"Region = 'WA'", S"BirthDate
                                    DESC");
      PrintResults(rows);
      // Search using a user-defined value
      rows = employeesTable->Select(S"BirthDate > #01/01/1964#");
      PrintResults(rows);
      // Search using the SUBSTRING expression
      rows = employeesTable->Select(S"SUBSTRING(HomePhone,2,3) =
                                    '206'");
      PrintResults(rows);
   }
   catch(Exception* e)
   {
      Console::WriteLine(e->Message);
   }
#pragma pop_macro("new")
}

Sorting, Searching, and Filtering Data with DataView Objects

When programming "true" .NET applications—as opposed to mixed mode applications—DataView objects are used to provide data binding between an application's data and Windows Forms (and Web Forms) controls. However, as this chapter is about using ADO.NET in the context of an MFC application, I think of the DataView being associated with the DataTable much as a CView is associated with a CDocument. Therefore, for our purposes DataView objects allow you to create multiple concurrent views on the same data so that any change to the data is realized by all the views—depending on their filter.

Table 63 DataViewRowState Enumeration Values

Member Name Description
AddedReturns new rows.
CurrentRowsAll current rows—including new, changed, and unchanged rows.
DetachedRows marked as deleted, but not yet removed from the collection.
ModifiedCurrentEach DataRow object maintains two versions of its data—an "original" version and a "modified" version. This facilitates such things as the batch operations where you can cancel edits, as seen in "Batch Row Changes." The ModifiedCurrent enumeration simply specifies that you want the current versions of modified rows. (Compare with ModifiedOriginal.)
ModifiedOriginalSpecifies that you want the original values of any modified rows. Compare with ModifiedCurrent, which allows you to obtain the current values.
NoneNo rows are returned.
OriginalRowsThis will return all of the original rows, including those that have been deleted or modified.
UnchangedOnly returns rows that have not been modified.

While it's not always obvious, each DataTable has a built-in DataView object associated with it. This view can be accessed via the DataTable::DefaultView property. Additionally, you can create as many DataView objects on your DataTable as your application needs. Typically these DataView objects are created in order to provide a filtered view of your data. Therefore, in this section you'll first see how to create filtered views—both by column value and by row state—and then how to sort and search your view's data. Note that I'll be defining new DataView objects in the code snippets in this section, as most times when a DataView is used it is because the application needs multiple views on the same data. However, you can apply the same techniques to the DataTable::DefaultView if your application has no need for a second view.

Filtering on Row State Information

In the section entitled "Working with Row State Information" you learned about the DataRow::RowState property and how various operations affect its value. In addition to being able to create views that are filtered on column values, you can also create filtered views specific to rows having a given RowState value. In fact, implementing this feature can be a very powerful addition to your application. For example, let's say that in your disconnected application you wish to provide an Undo feature for any changes the user has made to the DataTable. As you'll soon see, you could easily construct a view and display a dialog with all modified, added, or deleted rows so that the user could choose which ones were to be undone. You could also use the same strategy in presenting a dialog that would allow the user to confirm which data to actually update with the server data source. This is all done simply by instantiating a DataView object and setting its RowStateFilter property to one of the DataViewRowState enumeration values shown in Table 63.

The following code was once again run against the Employees table, with the difference being that this time I specified in the data adapter's constructor that I only wanted records with EmployeeID values less than 4. (This was done merely to produce a shorter printout from the example code.)

void DataViewFilterByRowState()
{
#pragma push_macro("new")
#undef new
   try
   {
      // Add rows
      DataRow* row1 = employeesTable->NewRow();
      row1->Item["FirstName"] = S"Fred";
      row1->Item["LastName"] = S"Flintstone";
      employeesTable->Rows->Add(row1);
      // Edit row
      employeesTable->Rows->Item[0]->Item[S"FirstName"] = S"Test";

      // Delete row
      employeesTable->Rows->Item[1]->Delete();
      PrintDataViewInfo(DataViewRowState::OriginalRows);
      PrintDataViewInfo(DataViewRowState::CurrentRows);
      PrintDataViewInfo(DataViewRowState::Added);
      PrintDataViewInfo(DataViewRowState::Deleted);
      PrintDataViewInfo(DataViewRowState::ModifiedCurrent);
      PrintDataViewInfo(DataViewRowState::ModifiedOriginal);
      PrintDataViewInfo(DataViewRowState::Unchanged);
   }
   catch(Exception* e)
   {
      Console::WriteLine(e->Message);
   }
#pragma pop_macro("new")
}

As you can see, the first thing I did was simply to add a new row, edit an existing row, and then delete a row. The PrintDataViewInfo function (shown next) is then called to test how these three changes (four if you include the initial reading of the data) would impact a DataView using each of the various DataViewRowState enumerations.

void PrintDataViewInfo(DataViewRowState rowStateFilter)
{
#pragma push_macro("new")
#undef new
   try
   {
      DataView* view = new DataView(employeesTable);
      view->RowStateFilter = rowStateFilter;
      Console::WriteLine(S"Using RowStateFilter = {0}",
                         __box(view->RowStateFilter));
      Console::WriteLine(S"Row count = {0}", __box(view->Count));
      String* format = S"{0,-3} {1, -10} {2}";
      Console::WriteLine(format, S"Row", S"First Name", S"Last Name");
      for (int i = 0; i < view->Count; i++)
      {
         Console::WriteLine(format,
                            __box(i),
                            view->Item[i]->Item[S"FirstName"],
                            view->Item[i]->Item[S"LastName"]);
      }
      Console::WriteLine();
   }
   catch(Exception* e)
   {
      Console::WriteLine(e->Message);
   }
#pragma pop_macro("new")
}

As you can see, the PrintDataViewInfo function constructs a DataView object based on the Employees table, sets the RowStateFilter to the passed DataViewRowState value, and then simply enumerates and outputs the records for that newly created view. Here is the output from running these two functions:

Using RowStateFilter Added
Row count = 1
Row First Name Last Name
0   Fred       Flintstone

Using RowStateFilter OriginalRows
Row count = 3
Row First Name Last Name
0   Nancy      Davolio
1   Andrew     Fuller
2   Janet      Leverling

Using RowStateFilter Deleted
Row count = 1
Row First Name Last Name
0   Andrew     Fuller

Using RowStateFilter CurrentRows
Row count = 3
Row First Name Last Name
0   Test       Davolio
1   Janet      Leverling
2   Fred       Flintstone

Using RowStateFilter ModifiedOriginal
Row count = 1
Row First Name Last Name
0   Nancy      Davolio

Using RowStateFilter ModifiedCurrent
Row count = 1
Row First Name Last Name
0   Test       Davolio

As you can see, with the DataView you can retrieve the original rows that were read into the DataTable, filter only added or deleted rows, view all current rows (which is what the DataTable::DefaultView does), or even specify that you want to see only modified rows (either the original values or the current values).

Filtering on Column Values

Much as you can use the DataTable::Select method to search for rows giving a search criteria, you can also search DataView objects via the DataView::RowFilter property. The main difference is that the Select method returns an array of DataRow objects, while the RowFilter property simply changes the records that the DataView presents when enumerating the row collection or requesting a specific row (via the Item property or one of the search methods).

In addition, the RowFilter takes a String parameter that acts as the search criterion that allows the same expression values as the Select method. Therefore, I'll refer you back to the "Searching (and Sorting) on Column Values" section in order to see examples of what types of expressions you can pass to the RowFilter property.

Sorting

Along with filtering DataView objects, you can also sort them via the DataView::Sort property. In order to set this value, simply specify the name of one or more columns separated by commas and include either ASC for (ascending sort) or DESC (for descending sort). Note that if you do not specify ASC or DESC for a given column, then its sort order defaults to ascending.

...

DataView* view = new DataView(employeesTable);
// Sort by a single column in ascending order
view->Sort = S"LastName";
// Sort by birthdate in descending order
view->Sort = S"BirthDate DESC";
// Sort by multiple columns in various orders
view->Sort = S"LastName, BirthDate DESC, Title";

Extending MFC Applications with the .NET Framework
By Tom Archer and Nishant Sivakumar
ISBN: 032117352X
Addison-Wesley

# # #



About the Author

Tom Archer - MSFT

I am a Program Manager and Content Strategist for the Microsoft MSDN Online team managing the Windows Vista and Visual C++ developer centers. Before being employed at Microsoft, I was awarded MVP status for the Visual C++ product. A 20+ year veteran of programming with various languages - C++, C, Assembler, RPG III/400, PL/I, etc. - I've also written many technical books (Inside C#, Extending MFC Applications with the .NET Framework, Visual C++.NET Bible, etc.) and 100+ online articles.

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • Today's "average" business in general is ever more reliant on technology and the Internet. Mobility is the most often cited business trend that has transformed the way many of us work and communicate. From an IT security perspective, this means that protection methods and tools from even a few years ago are rapidly becoming "unfit for purpose." This guide provides crucial facts to assist you in building a robust business case, meeting the demands of your business, and protecting against threats now and in the …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds