Home > Articles

This chapter is from the book

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 DataRowCollection 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 DataRowCollection—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 MissingSchemaAction 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 6-3. DataViewRowState Enumeration Values

Member Name

Description

Added

Returns new rows.

CurrentRows

All current rows—including new, changed, and unchanged rows.

Detached

Rows marked as deleted, but not yet removed from the collection.

ModifiedCurrent

Each 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.)

ModifiedOriginal

Specifies that you want the original values of any modified rows. Compare with ModifiedCurrent, which allows you to obtain the current values.

None

No rows are returned.

OriginalRows

This will return all of the original rows, including those that have been deleted or modified.

Unchanged

Only 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 6-3.

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";

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020