Search code examples
delphistack-overflowtoggleswitch

I got Stack overflow error in an OnClick event in Delphi 10.3.3


Ok... I have this form that has toggleSwitch in it and the user has to click on them and nothing else happens just yet... later I'm gonna have UPDATE query in each but for absolutely doing nothing I get a stack overflow error. I just do this it has to check if the Switch is in OFF mode then it has to turn it on or else... Please help me with this one

NOTE: I have similar applications that work fine with ToggleSwitches but this one is funny

procedure TUserAccess_.ToggleSwitch1Click(Sender: TObject);
begin
 if ToggleSwitch1.State = tssOff then
  ToggleSwitch1.State:= tssOn
 else
  ToggleSwitch1.State:= tssOff
end;

Solution

  • This is very expected.

    If you have a function that unconditionally calls itself, you will -- in theory -- get an infinite sequence of function calls. In practice, you will get a stack overflow.

    (To get a feeling for this, try to run

    procedure TForm1.Button1Click(Sender: TObject);
    begin
      Button1Click(Sender);
    end;
    

    or something similar.)

    In this case, the user clicks the toggle switch. Thus, its OnClick handler is called. But this one changes the toggle switch's state, which also triggers the OnClick handler, because that's how the control communicates that its state has been changed. So this code is run again, the state is changed again by your code, and the OnClick handler is called again. And so on for quite some time.

    Hence, you get a stack overflow. (And if you hadn't in some theoretical computer, you'd spent the rest of your application's life going further down this recursion.)

    You do know that the switch is toggled automatically when you click it, do you?

    Consequently, there is no need for your code at all.