Quick question I cannot find any information on.
On one of my components I am creating I have a value which is of Integer type.
I need to allow only values entered in the Object Inspector to be between 0-10, anything that falls outside of this range should display a message to say that the value inputted is not appropriate, and then return the focus back to the Delphi Object Inspector.
Example:
TMyComponent = class(TComponent)
private
FRangeVal: Integer;
procedure SetRangeVal(const Value: Integer);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property RangeVal: Integer read FRangeVal write SetRangeVal default 0;
end;
...
procedure SetRangeVal(const Value: Integer);
var
OldValue: Integer;
begin
OldValue := Value;
if (Value < 0) or (Value > 10) then
begin
MessageDlg('Please enter a value between 0-10', mtError, [mbOK], 0);
// FRangeVal := OldValue; ?? revert to the last value that worked
// return focus back to property in Inspector ??
end
else
begin
if Value <> FRangeVal then
begin
FRangeVal := Value;
end;
end;
end;
Do I need to raise some kind of special built in exception that I am unaware of maybe? The above works with my message box popping up, but focus to the culprit property in the Object Inspector is lost and I have to re click back into it to change the value again. If the entered value is bad I just want to show the message and return the focus so I can quickly enter a new value.
PS, code above was written in the web browser hence the original question showed I did not use the setter SetRangeVal for the property RangeVal – this was just a typing mistake.
First, if your property can only contain values between
0and10, don’t define it as a vague integer property; define it as a subtype with a defined range of values:Now you can let the compiler and IDE handle checking for allowable values without doing anything yourself. (The IDE wlll handle the exception and reverting back to the previous value if an invalid value is entered.)