你根本不需要TRole枚舉。只需使用條目填充ComboBox,以使其索引對應於數據庫值(0 =管理員; 1 =普通用戶)。還要將ComboBox的Style屬性設置爲csDropDownList。
procedure PopulateComboBox(const cb: TComboBox);
begin
cb.Clear;
cb.Items.Add('Administrator'); // ItemIndex = 0
cb.Items.Add('Common User'); // ItemIndex = 1
end;
現在,當你使用SQL請求,讓您的數據應用角色列的值直接組合框的ItemIndex屬性:
Query.SQL.Text := 'select Name, Role from table where ID = :ID';
...
if Query.FieldByName('Role').AsInteger in [0..1] then
RoleComboBox.ItemIndex := Query.FieldByName('Role').AsInteger
else
raise Exception.Create('Role column value must be in range of 0..1');
你幾乎是相同的,當你保存的作用到數據庫。使用ItemIndex屬性作爲要保存的值:
if RoleComboBox.ItemIndex in [0..1] then
begin
...
Query.SQL.Text := 'update table set Role = :Role where ID = :ID';
Query.ParamByName('Role').AsInteger := RoleComboBox.ItemIndex;
Query.ExecSQL;
end
else
raise Exception.Create('Invalid role index');
幾乎在那裏......問題是它需要在數據庫中保存爲** INTEGER **。如果我想將它們保存爲字符串,則您的方法可行 –
不正如我所說的,您使用組合框的ItemIndex屬性,該屬性是一個整數,並與您的字段完全對應。 – Dsm
因此,在這種情況下,我不會使用TDBComboBox來保存這個字段,而是一個普通的TComboBox並通過ItemIndex手動保存? –