1. Home
  2. Computing & Technology
  3. Delphi Programming

Focus the First Entry Control in a Container
Example: "Panel1.Focus_First_Edit_Box"

By Zarko Gajic, About.com

In any decently complex form design you will probably have edit controls (edit boxes, drop down lists, radio buttons, check boxes, etc) contained within a parent container control (TPanel, TGroupBox, ...).

Depending on the user interface design of your application you might have groups of container type controls.

In any data aware (database) application you probably have db-aware controls dropped on some container connected to a TDataSource connected to a TDBNavigator.

When you click the "Edit" or "Insert" buttons on the DBNavigator you want the "first" control in the group to receive the input focus - to allow for faster data input.

The FocusFirstEntryControl procedure will set the input focus to the first control in a container that is capable of receiving the focus:

procedure FocusFirstEntryControl(const container : TWinControl) ;
var
  index : integer;
begin
  for index := 0 to -1 + container.ControlCount do
  begin
    if container.Controls[index] is TWinControl then
    begin
      TWinControl(container.Controls[index]).SetFocus;
      Break;
    end;
  end;
end;

Note: the code uses ControlCount and Controls properties of a TWinControl descendant to access all controls that list some control as their Parent property.

The "AS" and "IS" operators are used to check if a control contained in a parent control can receive the focus (and set it).

Here's an example of usage:

begin
  //set the input focus to the first
  //"editable" control in "GroupBox1"

  FocusFirstEntryControl(GroupBox1) ;
end;

Delphi tips navigator:
» Iterating Over a Set type Variable in Delphi - Using For .. In Set_Values
« Implementing "Contains Focus" for Delphi's Container Controls: TPanel, TGroupBox, ...

More Delphi Programming Quick Tips
Zarko Gajic
Guide since 1998

Zarko Gajic
Delphi Programming Guide

Explore Delphi Programming
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. Delphi 2007 Tips
  7. Focus the First Entry Control in a Container in Delphi Applications

©2009 About.com, a part of The New York Times Company.

All rights reserved.