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];
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。Cells[ACol, ARow] := '值' 仍可寫入,需另行防護。OnGetCellProps 設定 ReadOnly 屬性,更語意化。善用 OnSelectCell 動態切換 goEditing,以極少程式碼實現 TStringGrid 欄位級唯讀控制,適合快速開發與維護。