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;
if ActiveControl IS TDBGrid then
begin
with ActiveControl AS TDBGrid do
if SelectedIndex < pred(fieldcount) then
SelectedIndex := SelectedIndex + 1
else
SelectedIndex := 0
end
else
SelectNext(ActiveControl AS TWinControl, True, True)
end
else
if Key = #2 then
SelectNext(ActiveControl AS TWinControl, False, True)
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;
TDBGrid* DBGrid = dynamic_cast(ActiveControl);
if (DBGrid)
{
if (DBGrid->SelectedIndex < dbgrid->FieldCount-1)
DBGrid->SelectedIndex += 1;
else
DBGrid->SelectedIndex = 0;
}
else
SelectNext(ActiveControl, true, true);
}
else
if (Key == 2)
SelectNext(ActiveControl, false, true);
}