views:

227

answers:

2

I would like a button to change a label between being visible and not visible when clicked. I Tried the following code, but it doesnt work:

Var:
  Hidden : Boolean;
Begin
  If Hidden = True
    Then 
      Begin
        Label6.Visible := True;
        Hidden := False;
      End;
  If Hidden = False
    Then
      Begin
        Label6.Visible := False;
        Hidden := True;
      End;

It compiles, but doesn't work!

+2  A: 

Do this:

 Label6.Visible := not Label6.Visible;

That's all the code you need.

Also, if you're going going to address the label in code, please give it a proper identifying name (like lblCountOfMatches or something).

Finally, the reason your code is not working is that Hidden is never set. It will default to false when declared. If you want to use the code you have now (which is too verbose) you must issue:

 Hidden := Label6.Visible

before inspecting Hidden.

Larry Lustig
Worked Perfectly, Thanks!
Chris55
A: 

The problem is two-fold: you declared a local variable which you then try to compare and you execute both comparisons even if the first one was processed.

You also don't need the boolean: you can just check if it's currently visible

What you should be doing is therefore something like this:

begin 
  if Label6.Visible then  
    Label6.Visible := False
  else
    Label6.Visible := True; 
end;

Or the even simpler:

begin
  Label6.Visible := not Label6.Visible;
end;
Michael Madsen
Hidden is declared globally, but i just put it in here to show what i was using. I tried your method but it didn't work! The label goes from visible to hidden, but does not become visible again!
Chris55