OnExit只在离开表格时才会发生,应该在OnSelectCell事件上也加上校验。
如下例,CheckData函数检查指定单元数据的合法性,在OnSelectCell和
OnExit事件中调用该函数进行校验。
function TForm1.CheckData(Row, Col: integer): boolean;
{对指定单元数据进行校验,要求数据必须为整数}
begin
Result := True;
if StringGrid1.Cells[Col, Row] = '' then
Exit;
try
StrToInt(StringGrid1.Cells[Col, Row]);
except
ShowMessage('Cell(' + IntToStr(Row) + ',' + IntToStr(Col) + ')' +
' is not a valid integer value');
Result := False;
end;
end;

procedure TForm1.StringGrid1SelectCell(Sender: TObject; Col, Row: Integer;
var CanSelect: Boolean);
begin
CanSelect := CheckData(StringGrid1.Row, StringGrid1.Col);
end;

procedure TForm1.StringGrid1Exit(Sender: TObject);
begin
if not CheckData(StringGrid1.Row, StringGrid1.Col) then
StringGrid1.SetFocus;
end;
const
eKeyViol=9729; //主鍵必須唯一
eReqdErr=9732; //主鍵不能為空
......
procedure TDataModule1.Q_XLSPostError(DataSet: TDataSet; E: EDatabaseError;
var Action: TDataAction);
begin
if (E is EDBEngineError) then
if (E as EDBEngineError).Errors[0].ErrorCode=eKeyViol then
begin
MessageDlg('提交失敗:成本項目名稱不能重復!',mtInformation,[mbOK],0);
Abort;
end
else if (E as EDBEngineError).Errors[0].ErrorCode=eReqdErr then
begin
MessageDlg('提交失敗:成本項目名稱不能為空!',mtInformation,[mbOK],0);
Abort;
end;
end;
如下例,CheckData函数检查指定单元数据的合法性,在OnSelectCell和
OnExit事件中调用该函数进行校验。



























在相關數據表中(table,adoquery)的OnPostError()事件中判斷:
......




















使焦点返回Grid.SelectedIndex := n;
取消修改
abort;