Search code examples
delphiviewproceduredfm

Assigning a value to a Label using procedures (Delphi)


I've been trying to assign a value to a Label (inserted by a TextBox) using procedures. Here's what I have so far:

type
  TfrmM8E1 = class(TForm)
    Button1: TButton;
    txt1: TEdit;
    lbl1: TLabel;
    procedure Button1Click(Sender: TObject);
    procedure Labels(a1: Integer);
    procedure DataInput(var a1 : Integer);
  private
  public
  end;

var
  frmM8E1: TfrmM8E1;

implementation

{$R *.dfm}

procedure TfrmM8E1.Button1Click(Sender: TObject);
var
  a: Integer;
begin
  // calls both procedures
  DataInput(a);
  Labels(a);
end;

Procedure TfrmM8E1.DataInput(var a1 : Integer);
begin
  a1 := StrToInt(frmM8E1.txt1.Text);
  // Receives a value from txt1(which is a textbox) and stores it in "a1".
end;

Procedure TfrmM8E1.Labels(a1 : Integer);
begin
  frmM8E1.lbl1.Caption := IntToStr(a1);
  // Assign the value of a1 to the label
end;

end.

Once the program runs, it doesn't show in my Label the value inserted in the TextBox.

Any idea why it is not working?

If you do know how to make the main idea work, assign a value to a Label inserted by a TextBox throughout the usage of procedures, great! Forget my code and let me take a look in yours :).

Otherwise, if you know, or at least have a hint about, what I should change in my code, even better!


Solution

  • Your code works for me, at least as VCL code. There as a lot of non-axiomatic stuff here, like you generally shouldn't reference the form variable from the object's methods. What if you want two forms later? Or what if that variable is not set?

    The idiomatic way to do it would be more like:

    procedure TForm1.Button1Click(Sender: TObject);
    begin
       Label1.Caption := Edit1.Text;
    end;
    

    You could put some validation in there to make sure it was a number, like

    Label1.Caption := Validate(Edit1.Text);
    

    And then Validate could be something like:

    function TForm1.Validate(S: String): String;
    var I: Integer;
    begin
       I := StrToIntDef(S, -1);
       if I = -1 then Result := 'Invalid positive integer.'
       else Result := S;
       end;
    

    Just for instance.

    EDIT: Word correction.