数据输入合法性检查

来源:互联网 发布:粤城电器淘宝店怎么样 编辑:程序博客网 时间:2024/05/01 20:57
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;  

 

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

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;

 

使焦点返回Grid.SelectedIndex := n;

取消修改

abort;

原创粉丝点击