Question:
I am using a simple grid with names and numbers, and I have the fields set as required in the database. I would like to know how to trap the errors in a TDBGrid
.
To give you some background:
I have defined/created a table using Database Desktop. I am trying to use the TDBGrid
as an interface for the user to edit the table. The table contains a Date field, two Alpha fields and several Numeric fields. All of the fields are marked as “required.”
Since the fields are “required,” if I “clear” any of the grid’s cells and press the up or down arrow to select another record (I assume thegrid is sending a post event), I get the following error:
This is what I’m looking to trap. I assumed I would detect this in n errorhandler and set focus to the field that caused the error.Project TEST.EXE raised exception class EdatabaseError with message ‘Field’ (whichever field is empty) must have a value. Process stopped. Use Step or Run to continue. [OK]
One additional piece of info: After the above error message, I can press the Run button and get the following dialog box:
Press OK, and you’re back at the record and cell you were editing.Field ‘Player’ must have a value [OK]
I would like to trap the “EdatabaseError” error, display a similar dialogbox, and set focus back to the empty cell. It sounds simple; however, I have been unable to find any examples using a TDBGrid
. All of the examples I have seen use a “TEdit” box, assign the value to the field and post to the table using a try .. except
.
Is there a way to do what I am attempting? I would like to make it ageneral error handler by “typecasting” or any other means you cansuggest.
Answer:
First, look in the online help under TTable
. Select the “Events”hyperlink, and look up the OnEditError
event. This is where you should beable to trap the message. The OnEditError
procedure is as follows:
When you do an event handler for this, it’ll look like so:procedure(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction) ofobject;
What you’ll do in the method is get the message property value of theEDatabaseError exception:procedure Table1EditError(DataSet: TDataSet; E: EDatabaseError; var Action:TDataAction)beginend;
This should work. However, note that I’m doing this off the top of my head, socheck this stuff out well.procedure Table1EditError(DataSet: TDataSet; E: EDatabaseError; var Action:TDataAction)var errMsg : String;begin errMsg := E.Message; {Find the sub-string that shows a required field error – usu. “must have a value” works.} if (Pos(‘must have a value’, errMsg) > 0) then {Do whatever processing you want in response to this error}end;