Delphi Programming

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

How to focus a specific cell in a DBGrid

By Zarko Gajic, About.com

Here's a simple trick to set the input focus to a specific cell of a TDBGrid component. Given the DBGrid's active row and field name (or the column index) the cell receives the input focus and becomes active.

The FocusCell procedure (two overloaded versions) receives a DBGrid as the first parameter and the name of the field you want to set the input focus to, as the second parameter.

~~~~~~~~~~~~~~~~~~~~~~~~~
procedure FocusCell(
   const DBGrid : TDBGrid;
   const column : integer) ; overload;
begin
   with TStringGrid(DBGrid) do
   begin
     Col := column;
     SetFocus;
   end;
end;

procedure FocusCell(
   const DBGrid : TDBGrid;
   const fieldName : string) ; overload;
var
   column : integer;
   idx : integer;
begin
   column := 0;
   for i:= 0 to -1 + DBGrid.Columns.Count do
   begin
     if DBGrid.Columns[idx].FieldName = fieldName then
     begin
       column := 1 + idx;
       Break;
     end;
   end;

   if column > 0 then FocusCell(DBGrid,column) ;
end;
~~~~~~~~~~~~~~~~~~~~~~~~~

Usage (suppose a dataset with field "ContactName" is displayed by "DBGrid1"):
  FocusCell(DBGrid1,'ContactName') ;

More TDBGrid related tips and tricks

Delphi tips navigator:
» The role of the "AOwner" parameter in the Create constructor
« How to click-and-select a line in TMemo Delphi component

More Delphi Programming Quick Tips

Explore Delphi Programming

More from About.com

Delphi Programming

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Using Data (DB) Controls
  5. How to focus a specific cell (by field name) in a DBGrid Delphi component

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

All rights reserved.