Prevent a DBGrid from adding a register when it is positioned beyond the last  

Send By: Q3 Team
Web : www.q3.nu
Email: dlib@q3.nu
Date: 07/09/00

Tip accessed 672 times

 


Useful when we want to give the opportunity to change data, but not of adding them.

Is enough to put this code inside the BeforeInsert event of the table:


 	   procedure TForm1.Table1BeforeInsert(DataSet: TDataset);
 	   begin
 	     Abort;
 	   end;




Another manner to make it:

Put this code into OnkeyDown event of the DBGrid:


 procedure TForm1.DBGrid1KeyDown(Sender: TObject; var Key: Word;
   Shift: TShiftState);
 begin
      if (Key = VK_DOWN) then
        begin
          TTable1.DisableControls;
          TTable1.Next;
          if TTable1.EOF then
            Key := 0
          else
            TTable1.Prior;
          TTable1.EnableControls;
         end ;
 end;





Rafa (rafael.alba@platea.pntic.mec.es) said us:
What does it happen if they press the TAB key in the last column of the DBGrid...? HORROR!!! they adds a register...

Here is my code to solve it:


        procedure TForm1.DBGrid1KeyDown(Sender: TObject; var Key: Word;
                  Shift: TShiftState);
        if (Key = VK_DOWN) or ((Key = VK_TAB) and (TDrawGrid(DBGrid1).Col = 2)) then
        {en este caso, el dbgrid tiene DOS columnas...}
        begin
          Tabla1.DisableControls;
          Tabla1.Next;
          if Tabla1.EOF then
            Key := 0
          else
            Tabla1.Prior;
          Tabla1.EnableControls;
         end ;



It is good, but... this is better:


 procedure TForm1.DBGrid1KeyDown(Sender: TObject; var Key: Word;
   Shift: TShiftState);
 begin
 if (Key = VK_DOWN) or
    ( (Key = VK_TAB) and
    (DBGrid1.SelectedIndex = DbGrid1.Columns.Count-1) ) then
    begin
      with (Sender as TDbGrid).DataSource.DataSet do
      begin
        DisableControls;
        Next;
        if EOF then Key := 0 else Table1.Prior;
        EnableControls;
      end;
    end;
 end;




Sent by: DARIO ALVAREZ ARANDA (dalvarez@udesoft.com)

I have read the tip 59 and him fact some improvements to make it completely generic that can be good for any DBGrid, or for a group of DBGrid:


 
   with (Sender as TDbGrid) do
     if (Key = VK_DOWN) or ((Key = VK_TAB) and (SelectedIndex = Columns.Count-1)) then
      begin
        DataSource.DataSet.DisableControls;
        DataSource.DataSet.Next;
        if DataSource.DataSet.EOF then
          Key := 0
        else
          DataSource.DataSet.Prior;
        DataSource.DataSet.EnableControls;
      end;




Updated at 28/02/2000
Updated at 07/09/2000