FindKey (C++)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This code exemplifies the uses of the FindKey and FindNearest functions. This example requires a ClientDataset, a DataSource, a DBGrid, and a DBNavigator. Connect the DataSource to the DataSet and then connect the DBGrid to the DataSource. Also, the DBNavigator needs to be connected to the DataSource. Now you need to create two fields in the DataSet. Right-click on the TClientDataset component, select Fields Editor, create two fields named field1 and field2. Then specify the IndexDefs property for ClientDataSet in the Object Inspector. Add two indexdefs. The first one should have the Fields property set to field1 and the Name property set to field1index while the second one should have field2 and field2index.

Run the example, press the Create "DataSource" button, then add some records to the DBGrid with the aid of DBNavigator. After that, enter one of the values in any record in "field1" in the "Search for:" edit box. Press the "FindKey" button and observe the message that appears on the screen. Do the same with the "FindNearest" button.

Code

void __fastcall TForm2::btnCreateDSClick(TObject *Sender)
{
  /* Create a DataSet. */
  ClientDataSet1->CreateDataSet();

  /* After you create the DataSet, manually add some records with "DBNavigator". */
}

void __fastcall TForm2::btnFindKeyClick(TObject *Sender)
{
  /* Set the "IndexName" required by the "FindKey" method. */
  ClientDataSet1->IndexName = "field1index";

  /* Perform the search and inform the User through a message. */
  if (ClientDataSet1->FindKey(ARRAYOFCONST((SearchFor->Text))) == TRUE)
	{
	  ShowMessage(Format("""%s"" was found. Cursor moved to the record.", ARRAYOFCONST((SearchFor->Text))));
	} else
	{
	  ShowMessage(Format("""%s"" was not found.", ARRAYOFCONST((SearchFor->Text))));
	}
}

void __fastcall TForm2::btnFindNearestClick(TObject *Sender)
{
  /* Set the "IndexName" required by the "FindKey" method. */
  ClientDataSet1->IndexName = "field2index";

  /* Perform the search and inform the User through a message. */
  ClientDataSet1->FindNearest(ARRAYOFCONST((SearchFor->Text)));
  ShowMessage(Format("Nearest match for ""%s"" was found at record: %d",
	ARRAYOFCONST((SearchFor->Text, IntToStr(ClientDataSet1->RecNo)))));
}

void __fastcall TForm2::btnCloseDSClick(TObject *Sender)
{
  /* Close the DataSet. */
  ClientDataSet1->Close();
}

Uses