Board index » delphi » Key violation handling

Key violation handling

Hello,

        I am a novice programmer who is writing a small database
program and I have run into a snag.  I have set up a single field
lookup table that the user will populate.  I have keyed the table so
that there are no duplicate entries.  When I run the program and
purposely enter a duplicate value in the table, I get a Key Violation
error and it locks the program up.  My intention was to test the value
of the entry with the SetKey method and prevent posting the record
until the entry became unique.  Unfortunately, as soon as I hit enter
the program locks up before the code I wrote executes.  Is there any
way around this?  (disabling the enter/post property of the DBEdit
object for example?)  Any advice would be appreciated.

Thanks in advance,

Jim

 

Re:Key violation handling


I solve key violation errors by trapping the exception.  The procedure is
as follows:

Declare an exception handler as private.

   procedure MyException(Sender: TObject; E: Exception);

Take over the exception handler in FormCreate.

   Application.OnException := MyException;

Release the exception handler in FormClose.

   Application.OnException := Nil;

Implement the new exception handler.

procedure TMyForm.MyException(Sender: TObject; E: Exception);
begin
   if  E is EDBEngineError then
   begin
      if E.Message = 'Key violation' then
      begin
         MessageDlg(Format('Duplicate Key [%s]',
           [MyTableMyKeyField.Value]), mtError, [mbOK], 0);
         MyKeyField.SetFocus;
      end;
   end;
end;

John.

Other Threads