ColdZer0
ColdZer0

Reputation: 233

How to count up numbers in a label in delphi

I have a program containing a button and a label, I want the label to count up numbers so fast from 0 to 100000 for example.

I tried System.Diagnostics stopwatch but it's not as I want it.

procedure TForm1.Button1Click(Sender: TObject);
var
  sw: TStopwatch;
begin
  sw := TStopwatch.StartNew;
  Timer1.Enabled := True;
 end;

procedure TForm1.Timer1Timer(Sender: TObject);
var
  sw: TStopwatch;
begin
  sw.Start;
  label1.Caption := IntToStr(sw.ElapsedMilliseconds);
end;

Upvotes: 0

Views: 1333

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596948

TStopWatch (which you are not using correctly, BTW) is not the kind of counter you are looking for. You need a simple Integer variable instead, eg:

type
  TForm1 = class(TForm)
    Button1: TButton;
    Label1: TLabel;
    Timer1: TTimer;
    procedure Button1Click(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
  private
    Counter: Integer;
  end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Counter := 0;
  Label1.Caption := IntToStr(Counter);
  Timer1.Enabled := True;
end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  Inc(Counter);
  Label1.Caption := IntToStr(Counter);
  if Counter = 100000 then Timer1.Enabled := False;
end;

Upvotes: 1

Related Questions