Delphi Clinic C++Builder Gate Training & Consultancy Delphi Notes Weblog Dr.Bob's Webshop
Bob Swart (aka Dr.Bob) - Medical Officer Delphi 6 Developer's Guide
 Dr.Bob's Tip-Of-The-Hat #3
See Also: Delphi Papers, Columns and other Tip-Of-The-Hats

Enter as TAB (2)
In the previous Tip-Of-The-Hat item, we learned how to let the Enter work as TAB in your applications: how to move from one control to another using the Enter key instead of TAB. Based on some responses and feedback (keep it coming!), we'll now look at a way to let the Enter work as TAB inside a TDBGrid control.

The source with which we ended last time will move you from one control to another when you press the Enter key. However, inside a TDBGrid control it doesn't work: you still need to press TAB to move from one cell to another. Inside a TDBGrid control, we need to use the SelectedIndex property to go to the next field inside the grid (increment it by one to move to the next column). We must make sure SelectedIndex will not get a value higher than the FieldCount property (the number of fields in the grid), but in that case reset it to 0 to get to the first column again. The only thing left to do by the user is hit the arrow-down key to move to the next line in the grid.

  procedure TForm1.Form1KeyPress(Sender: TObject; var Key: Char);
  begin
    if Key = #13 then
    begin
      Key := #0; // Eat the Beep
      if ActiveControl IS TDBGrid then
      begin
        with ActiveControl AS TDBGrid do
          if SelectedIndex < pred(fieldcount) then
            SelectedIndex := SelectedIndex + 1 // next column
          else
            SelectedIndex := 0 // back to first
      end
      else // not (ActiveControl IS TDBGrid)
        SelectNext(ActiveControl AS TWinControl, True, True) // Forward
    end
    else // not (Key = #13)
      if Key = #2 then
        SelectNext(ActiveControl AS TWinControl, False, True) // Backward
  end;
Note that the code above is the OnKeyPress handler of the Form itself, so you should have set the KeyPreview property of the Form to true as well.

Using Borland C++Builder, we would have to extend the FormKeyPress from last time as follows:

  void __fastcall TForm1::FormKeyPress(TObject *Sender, char &Key)
  {
    if (Key == 13)
    {
      Key = 0; // Eat the Beep
      TDBGrid* DBGrid = dynamic_cast(ActiveControl);
      if (DBGrid)
      {
        if (DBGrid->SelectedIndex < dbgrid->FieldCount-1)
          DBGrid->SelectedIndex += 1; // next column
        else
          DBGrid->SelectedIndex = 0; // back to first
      }
      else // not (ActiveControl IS TDBGrid)
        SelectNext(ActiveControl, true, true); // Forward
    }
    else // not (Key = #13)
      if (Key == 2)
        SelectNext(ActiveControl, false, true); // Backward
  }

This webpage © 2001-2009 by Bob Swart (aka Dr.Bob - www.drbob42.com). All Rights Reserved.