首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi StringGrid 單欄唯讀技巧:OnSelectCell 動態切換 goEditing 選項

     編輯:Delphi

TStringGrid 預設整個格狀皆可編輯。若需特定欄 (如第 0、2、4 欄) 唯讀,可在 OnSelectCell 事件中依欄索引動態增減 goEditing 選項,無需自訂元件或複雜繼承。

核心程式碼


procedure TForm1.StringGrid1SelectCell(Sender: TObject; ACol, ARow: Integer;
  var CanSelect: Boolean);
begin
  // 偶數欄可編輯,奇數欄唯讀
  if ACol mod 2 = 0 then
    StringGrid1.Options := StringGrid1.Options + [goEditing]
  else
    StringGrid1.Options := StringGrid1.Options - [goEditing];
end;

運作原理

  • OnSelectCell 在使用者點選/導航到儲存格前觸發。
  • Options 為集合屬性,`+ [goEditing]` 啟用編輯模式,`- [goEditing]` 禁用。
  • 動態調整即時生效,下一個儲存格進入編輯狀態時已套用新設定。

進階變體

指定多欄唯讀 (陣列/集合判斷)


const ReadOnlyCols: set of Integer = [0, 2, 5]; // 第 1, 3, 6 欄唯讀
if ACol in ReadOnlyCols then
  StringGrid1.Options := StringGrid1.Options - [goEditing]
else
  StringGrid1.Options := StringGrid1.Options + [goEditing];

依資料內容決定 (如 ID 欄不可改)


if (ARow > 0) and (StringGrid1.Cells[0, ARow] <> '') then // 假設第 0 欄為 ID
  StringGrid1.Options := StringGrid1.Options - [goEditing]
else
  StringGrid1.Options := StringGrid1.Options + [goEditing];

注意事項

  • 若 goRowSelect 在 Options 中,整列選取時 OnSelectCell 可能不觸發,需移除 goRowSelect。
  • 此技巧僅影響 UI 編輯狀態,若程式碼直接指派 Cells[ACol, ARow] := '值' 仍可寫入,需另行防護。
  • Delphi 10.4+ 可改用 OnGetCellProps 設定 ReadOnly 屬性,更語意化。

小結

善用 OnSelectCell 動態切換 goEditing,以極少程式碼實現 TStringGrid 欄位級唯讀控制,適合快速開發與維護。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved