2006. február 20., hétfő

Get the text in a TDBGrid cell before focus is moved to another cell


Problem/Question/Abstract:

How can I get the text in a cell (for TDBGrid) as the user types, but before focus is moved from that cell?

Answer:

Solve 1:

{ ... }
type
  {To access TCustomGrid.InplaceEditor declared as protected}
  TMyGrid = class(TDBGrid);

procedure TForm1.DBGrid1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  with TMyGrid(DBGrid1) do
    if EditorMode then
      Label1.Caption := InplaceEditor.Text;
end;


Solve 2:

My solution is very similar to Solve 1 but avoids the need for a subclass. You may prefer to have the action take place in KeyDown or KeyPress but these events generate problems when you start to edit a cell i.e. handling backspace or delete (where was the caret). For this reason it is a lot less hassle to deal with KeyUp, with this event the Editor content has been established by the time it fires. DBGrid1.Controls[0] is the InplaceEditor and below I check for its existence before trying to use it. As it is, it does not handle pasted text. You might do this by trapping WM_PASTE then testing if the Grid (not the InplaceEditor) is the ActiveControl.

procedure TForm1.DBGrid1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if DBGrid1.ControlCount > 0 then
    Edit1.Text := TEdit(DBGrid1.Controls[0]).Text;
end;

Nincsenek megjegyzések:

Megjegyzés küldése