Lesson 35

Programming Databases, Part 2

The simple programs described in the previous lesson are hardly commercial-caliber database applications, but they do let you perform basic database operations with amazingly little code.

In this lesson, you learn how to add a few new features to the programs described in Lesson 34. You learn how to add searching, filtering, and sorting to the programs to make finding data easier.

Searching

In a large database, it can be hard to locate a particular value. A program can make finding records easier by using the BindingContext's Find method. This method takes as parameters the name of a field to search and the value that it should find. It returns the index of the first record that has the desired value.

For example, the following code searches the data in the BindingSource named contactsBindingSource for a record with FirstName value equal to Kim:

int recordNumber = contactsBindingSource.Find("FirstName", "Kim");

Having found the index of the target record, you can then highlight it in some way for the user to see. For example, recall that a BindingSource's CurrencyManager controls the current position within the data. The following code makes the current record be the record found by Find so any controls displaying the data will show this record:

contactsBindingSource.CurrencyManager.Position = recordNumber;

Get C# 24-Hour Trainer, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.