Executing a Search with Goto Methods

From RAD Studio
Jump to: navigation, search

Go Up to Using Indexes to Search for Records


To execute a search using Goto methods:

  1. Specify the index to use for the search. This is the same index that sorts the records in the dataset. To specify the index, use the IndexName or IndexFieldNames property.
  2. Open the dataset.
  3. Put the dataset in dsSetKey state by calling the SetKey method.
  4. Specify the value(s) to search on in the Fields property. Fields is a TFields object, which maintains an indexed list of field components you can access by specifying ordinal numbers corresponding to columns. The first column number in a dataset is 0.
  5. Search for and move to the first matching record found with GotoKey or GotoNearest.

For example, the following code, attached to a button's OnClick event, uses the GotoKey method to move to the first record where the first field in the index has a value that exactly matches the text in an edit box:

procedure TSearchDemo.SearchExactClick(Sender: TObject);
begin
  ClientDataSet1.SetKey;
  ClientDataSet1.Fields[0].AsString := Edit1.Text;
  if not ClientDataSet1.GotoKey then
    ShowMessage('Record not found');
end;
void __fastcall TSearchDemo::SearchExactClick(TObject *Sender)
{
  ClientDataSet1->SetKey();
  ClientDataSet1->Fields->Fields[0]->AsString = Edit1->Text;
  if (!ClientDataSet1->GotoKey())
    ShowMessage("Record not found");
}

GotoNearest is similar. It searches for the nearest match to a partial field value. It can be used only for string fields. For example,

Table1.SetKey;
Table1.Fields[0].AsString := 'Sm';
Table1.GotoNearest;
Table1->SetKey();
Table1->Fields->Fields[0]->AsString = "Sm";
Table1->GotoNearest();

If a record exists with "Sm" as the first two characters of the first indexed field's value, the cursor is positioned on that record. Otherwise, the position of the cursor does not change and GotoNearest returns False.

See Also