Mega Code Archive

 
Categories / Delphi / ADO Database
 

How to focus a specific cell (by field name) in a DBGrid Delphi component

Title: How to focus a specific cell (by field name) in a DBGrid Delphi component 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