FindField (C++)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example uses a button to copy the value of a field in the previous record into the corresponding field in the current record. The field to copy is specified by using FindField and the name of the field.

Code

void __fastcall TForm1::Button2Click(TObject *Sender)
{
  TBookmark SavePlace;
  Variant PrevValue;
  // Get a bookmark so that you can return to the same record.
  SavePlace = Customers->GetBookmark();
  try
  {
	// Move to prior record.}
	Customers->FindPrior();
	// get the value
	// This is the safe way to get the 'CustNo' field.
	PrevValue = Customers->FindField("Field2")->Value;
	// This is not the safe way to change the 'CustNo' field.
	// PrevValue = Customers->Fields->Fields[1]->Value;
/*
	Move back to the bookmark.
	This may not be the next record anymore
	if something else is changing the dataset asynchronously,
*/
	Customers->GotoBookmark(SavePlace);
	// Set the value.
	Customers->Edit();
	// This is the safe way to change the 'CustNo' field.
	Customers->FindField("Field2")->AsString = PrevValue;
	// This is not the safe way to change the 'CustNo' field.
	// Customers->Fields->Fields[1]->AsString = PrevValue;
	// Free the bookmark.
  }
  __finally
  {
	Customers->FreeBookmark(SavePlace);
  };
}

/*
To ensure that the button is disabled when there is no
previous record, the OnDataChange event of the DataSource
detects when you move to the beginning of the file (BOF
property becomes True) and disables the button. Detection
occurs on scrolling and editing, not on selection with the mouse.
*/
void __fastcall TForm1::DS2DataChange(TObject *Sender, TField *Field)
{
  if (Customers->Bof)
	Button2->Enabled = False;
  else
	Button2->Enabled = True;
}

Uses