TechTricks
Technical answers from the trenches 
 
 
 
 

     
   
Determining the Active Field Name
 
   
 Posted: 26 September 2000
 
   
 
 Applies to: All versions
 
   
 
Audience: Intermediate
 
       
   

Question: How can I determine the name of a field bound to the current control?

Answer: Assuming that you're already verified that an object is data-aware, the following code shows one way to do this:

function getFieldName : String;
begin

   with screen do
   begin

      if ( activeControl is tDBGrid ) then
         result := tDBGrid( activeControl ).selectedField.fullName

      else if ( activeControl is tDBEdit ) then
         result := tDBEdit( activeControl ).dataField

      else if ( activeControl is tDBCheckbox ) then
         result := tDBCheckbox( activeControl ).dataField

      else if ( activeControl is tDBMemo ) then
         result := tDBMemo( activeControl ).dataField

      else
         raise exception.create(
            'Can''t Get Field Name' + #10#10 + 'Reason: ' +
            'An unexpected object called getFieldName().' + #10 +
            'The activeControl is named ' + activeControl.Name );

   end; // with
end;

This works by carefully testing Screen.ActiveControl against a list of object types used in the application. When a match is found, the C-style typecast ensures that Delphi will treat ActiveControl as the appropriate type of object when resolving the property reference leading to the field name.

Remember that the C-style typecasting (tDBGrid( activeControl), for example) is not the preferred way to typecast objects. The following snippet an approach generally recommended by the experts:

   with ( ActiveControl as tDBGrid ) do
      result := selectedField.fullName

This is considered a superior approach because it raises an exception if the object cannot be cast as the desired class. The original code works for many cases, however, because the if statements do not return true unless activeControl can be treated as the class being tested. Different developers have different tastes in this area, so use the approach that matches your personal preferences or development standards.

Also, it is possible to use RTTI to handle many of the objects, however, you'll still need additional tests for objects that do not have DataField properties, e.g. tDBGrids and many third-party data-aware components.

Finally, note that you'll need to add references to a valid USES block for this to work. Use the Help files to determine the appropriate unit to add.

 

       

Top

Feedback About Paradox Delphi Assorted Web Stuff
 
 
Copyright © 2000-2004, techtricks.com; All Rights Reserved.
Acknowledgements, Disclaimers, Terms and Conditions.
Article last updated on 01 June 2003

 

Other Sites: Paradox, Delphi, Perl, Web Stuff, and More


 

[- End -]