傳統權限控制多透過 ActionList 對應資料庫權限表。本文分享利用每個控制項固有的 Tag 屬性(預設值 0,表示無需權限控制)實現精細權限管理的實作模式。
Tag 依序指派唯一正整數 (1, 2, 3...)。CheckBoxList 中列出所有權限名稱(選單與按鈕),順序必須與 Tag 指派順序完全一致。Privilege 字串欄位(預留 50 字元),以 0 表示「有權限/啟用」,1 表示「無權限/停用」。AnsiString qx = "";
for (int i = 1; i <= CheckListBox1.Items.Count; i++) {
qx += CheckListBox1.Checked[i-1] ? "0" : "1";
}
Sql = "UPDATE Operator SET Privilege = '" + qx + "' WHERE Operator_Name = '" + CboOperatorName.Text + "'";
FormShow 事件中讀取使用者權限字串,遍歷元件集合,依 Tag 值對應字串位置決定 Enabled 屬性。
if (UserName != "系統管理員") {
if (strPrivilege.Length == 0) { // 未設定權限:全部停用
for (int j = 0; j <= Parent.ComponentCount-1; j++) {
if (Parent.Components[j].Tag != 0) {
if (Parent.Components[j] is TMenuItem)
((TMenuItem)Parent.Components[j]).Enabled = false;
else if (Parent.Components[j] is TButton)
((TButton)Parent.Components[j]).Enabled = false;
}
}
} else { // 已設定權限:依字串逐項啟用/停用
for (int i = 1; i <= strPrivilege.Length; i++) {
string qx = strPrivilege.Substring(i, 1);
if (qx == "1") { // 無權限
for (int j = 0; j <= Parent.ComponentCount-1; j++) {
if (Parent.Components[j].Tag == i) {
if (Parent.Components[j] is TMenuItem)
((TMenuItem)Parent.Components[j]).Enabled = false;
else if (Parent.Components[j] is TButton)
((TButton)Parent.Components[j]).Enabled = false;
}
}
}
}
}
}
適用於 Windows Forms (Delphi/C++Builder/VB6 等) 應用程式,概念亦可移植至 Web 表單 (ASP.NET) 控制項 Attributes["Tag"] 實作。