A day or so ago I got thoroughly stuck solving a frustrating problem in my little program that somehow has grown to 14000+ lines of new code. It turned out to be an issue where creating a from would change my data before I could display it in the form. I had loaded the data first, then created to form. As a part of the OnCreate process I would load the values from my data into TEdit controls, but the OnChange event would fire while the control was being created, before I could write my value to it, and that OnChange event would assign default Edit.Text string to my variable before I could write the original value to the TEdit. Tedious, but solved, many hours later. It reminded me again of how I probably still haven't learned to use Delphi controls properly. Self-taught, you know.

But the good news, in the process of debugging this I figured out a way to prevent this problem and to make it a lot easier to handle OnEnter and OnChange events in forms where I had many controls, and I thought I'd share, at the risk of illustrating the obvious to all you pros.

Anyway, instead of creating separate OnEnter and OnChange event handlers for each control, I now do this:

procedure TProcessForm.OptGasFlowOptionsChange(Sender: TObject);
var Value:single;
begin
  if (Sender as TNxNumberEdit).Focused then
  begin
    Value:=(Sender as TNxNumberEdit).Value;
    case (Sender as TNxNumberEdit).Tag of
      0 : DaqProject.Options.DeltaT:=Value;
      1 : DaqProject.Options.FlowRate1:=Value;
      2 : DaqProject.Options.FlowRate2:=Value;
      3 : DaqProject.Options.FlowRate3:=Value;
      4 : DaqProject.Options.FlowRate4:=Value;
      5 : DaqProject.Options.PurgeRate:=Value;
      6 : DaqProject.Options.PurgeTime:=Value;
    end;
  end;
end;

The only thing you do differently when setting the properties of your controls is to set the tag number.

Of course, you could do this for other types of events, too, but don't try and mix different types of controls in these procedures. You can't include (Sender as TEdit) and (Sender as TCheckBox) code in the same procedure, for example. Also, the Values variable is not necessary, but it made the typing easier. I might take it out, later, probably after I get a stack overflow error.

Actually you can :)

as you can ask if Sender is TCheckBox :)

I had tried it as was getting invalid type reference errors, if I recall correctly.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.