Tuesday 19 June 2018

Why does TSpinEdit not enforce the MaxValue property?

With a TSpinEdit there is a property called 'MaxValue', from the name it implies that the maximum value for the control is what value you set for the property, but this is not the case. The property sets the maximum value for using the spin edit buttons, a user can enter a value exceeding the maximum value by using the keyboard up to the value of an Int64 (9,223,372,036,854,775,807).

This seems to have been done by design, but I cannot see a valid reason for this and it could be a little dangerous when being used to control the valid values entered.  

By putting the following in the OnChange event I've managed to get around the problem. Not sure if there is a better solution. 

if (Sender is TSpinEdit) then
begin
    if (Sender as TSpinEdit).Value > (Sender as TSpinEdit).MaxValue then
    begin
        (Sender as TSpinEdit).Value := (Sender as TSpinEdit).MaxValue;
    end;
end;



4 comments:

  1. with (Sender as TSpinEdit) do Value := Min(Value, MaxValue);

    No need to check if it's a TSpinEdit unless you assign the handler to something that is not a TSpinEdit...

    ReplyDelete
  2. I never use 'with' statements, they are a very very bad idea and have seen issues so many times when people have used them.

    ReplyDelete
  3. AFAIK, MaxValue is the maximum value for the spinner (the TUpDown part), not for the edit.

    ReplyDelete
    Replies
    1. Yes, the MaxValue is just for the spinner button not for the whole component (TCustomEdit with a TSpinButton). This is not clearly obvious at design time naming the property to SpinButtonMaxValue would help. I believe this could have been designed better.

      Delete