1. Computing

How to focus a specific cell in a DBGrid

From , former About.com Guide

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

©2013 About.com. All rights reserved.