將記錄指標移至目標記錄 → 呼叫 Delete 方法。無需將 TTable 設為編輯狀態。刪除後後續記錄前移,指標自動移至緊鄰下一筆。無內建確認對話框,開發應用時最佳實務:提供確認訊息框防止誤刪。
Delphi 提供兩種插入位置:目前指標處 (Insert) 或表尾 (Append)。但有索引表中兩者效果相同:新記錄依索引順序寫入。Append 僅適用無索引表(實務罕用),幾乎所有情況用 Insert。
三步驟:Insert 建立空白記錄 → 填充各欄位 → Post 寫入磁碟。填充傳送前考慮插入位置無意義。有索引表 Post 時自動依索引順序置入正確位置;無索引表則插入目前指標後。
with Table do
begin
Insert; { 插入空白記錄 }
<填充各欄位>
Post; { 寫入磁碟 }
end;
無索引表可用 Append 替代 Insert 插入表尾。
簡單應用可用單一陳述式插入帶多欄位值的新記錄。InsertRecord 將欄位賦值與 Post 合併。參數為欄位值陣列(方括號包裹,逗號分隔)。可從最左欄開始依次賦值任意多欄位,省略後續欄位以空值填充,明確指定空值用 nil。
InsertRecord(['2000', nil, nil, nil]); { 僅填前四欄:CustNo、Company、Addr1、Addr2 }
unit tt;
interface
uses SysUtils, Windows, Messages, Classes, Graphics, Controls,
StdCtrls, Forms, DBCtrls, DB, DBGrids, Buttons, DBTables, Grids,
ExtCtrls, Mask, Dialogs;
type
TForm1 = class(TForm)
DBGrid1: TDBGrid;
DBNavigator: TDBNavigator;
Panel1: TPanel;
DataSource1: TDataSource;
Panel2: TPanel;
CustomerTable: TTable;
BitBtn1: TBitBtn;
Label1: TLabel;
Label2: TLabel;
BitBtn2: TBitBtn;
BitBtn3: TBitBtn;
CustNoEdit: TEdit;
CompEdit: TEdit;
procedure FormCreate(Sender: TObject);
procedure BitBtn2Click(Sender: TObject);
procedure BitBtn3Click(Sender: TObject);
procedure FormActivate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
begin
CustomerTable.Open;
end;
procedure TForm1.BitBtn2Click(Sender: TObject); { 插入 }
begin
if (Length(CustNoEdit.Text)=0) and (Length(CompEdit.Text)=0) then
MessageDlg('沒有輸入新記錄的欄位值!', mtError, [mbCancel], 0)
else
with CustomerTable do
begin
IndexFieldNames := 'CustNo';
if FindKey([CustNoEdit.Text]) then
MessageDlg('已經存在這條記錄!', mtError, [mbCancel], 0)
else
InsertRecord([StrToInt(CustNoEdit.Text), CompEdit.Text, nil]);
CustNoEdit.Text := '';
CompEdit.Text := '';
end;
end;
procedure TForm1.BitBtn3Click(Sender: TObject); { 刪除 }
begin
if (Length(CustNoEdit.Text)=0) and (Length(CompEdit.Text)=0) then
MessageDlg('沒有輸入刪除記錄的欄位值!', mtError, [mbCancel], 0)
else
with CustomerTable do
begin
IndexFieldNames := 'CustNo';
if FindKey([CustNoEdit.Text]) then
begin
if MessageDlg('你確定要刪除這條記錄嗎?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then
Delete;
end
else
MessageDlg('沒有你要刪除的記錄!', mtError, [mbCancel], 0);
CustNoEdit.Text := '';
CompEdit.Text := '';
end;
end;
procedure TForm1.FormActivate(Sender: TObject);
begin
CustNoEdit.SetFocus;
end;
end.
插入前用 FindKey 檢查重複;刪除前確認對話框;操作後清空輸入框並設定焦點。