假設與dbgrid相連的表為table1,不可以重復的字段為:field1.
在field1的OnSetText事件中﹕
procedure TForm1.Table1field1SetText(Sender: TField; const Text: String);
begin
Table1.IndexName :='field1';
if table1.FindKey(['text']) then
begin
showmessage('error');
table1.FieldByName('field1').Value='';
exit;
end
else
table1.FieldByName('field1').Value:=text;
end;
参考
eKeyViol=9729;//主键重复时的错误值
procedure TForm1.Table1PostError(DataSet: TDataSet; E: EDatabaseError;
var Action: TDataAction);
begin
if (E is EDBEngineError) then
if(E as EDBEngineError).errors[0].Errorcode=eKeyViol then
begin
action:=daAbort;//挂起,中止程序继续执行
dataset.Cancel;
showmessage('不能重复');