Please note, the code from this post will work only for published properties!
To answer your question if there's a way to set a property value without using if statement, check the following overloaded functions.
The first one is for char, string, variant, integer, 64-bit integer, float, enumeration, set and dynamic array type of properties (phew). The second one is just for class type properties. Both will return True if given property exists and the value or object instance is successfuly assigned, False otherwise:
uses
TypInfo;
function TrySetPropValue(AInstance: TObject; const APropName: string;
const AValue: Variant): Boolean; overload;
begin
Result := True;
try
SetPropValue(AInstance, APropName, AValue);
except
Result := False;
end;
end;
function TrySetPropValue(AInstance: TObject; const APropName: string;
AValue: TObject): Boolean; overload;
begin
Result := True;
try
SetObjectProp(AInstance, APropName, AValue);
except
Result := False;
end;
end;
And the usage; when the Memo1.Lines
is set the, the second version of TrySetPropValue
is called:
procedure TForm1.Button1Click(Sender: TObject);
var
Strings: TStringList;
begin
TrySetPropValue(Memo1, 'Width', 250);
TrySetPropValue(Memo1, 'Height', 100);
TrySetPropValue(Memo1, 'ScrollBars', ssBoth);
Strings := TStringList.Create;
try
Strings.Add('First line');
Strings.Add('Second line');
TrySetPropValue(Memo1, 'Lines', Strings);
finally
Strings.Free;
end;
if not TrySetPropValue(Memo1, 'Height', 'String') then
ShowMessage('Property doesn''t exist or the value is invalid...');
if not TrySetPropValue(Memo1, 'Nonsense', 123456) then
ShowMessage('Property doesn''t exist or the value is invalid...');
end;
TypInfo.pas
– TLama Apr 1 '12 at 12:49