Maks244
Maks244

Reputation: 59

How to toggle visibility in Windows Forms C#

I have a couple of labels that change visibility a lot and when they do I just use

Label1.Visible = true;
Label2.Visible = true;
Label3.Visible = true;

or

Label1.Visible = false;
Label2.Visible = false;
Label3.Visible = false;

So to make my code more readable I want to put these in a function. But to do that I would need a function that toggles the visibility, not turns them on or off. Is this possible?

Upvotes: 2

Views: 2671

Answers (3)

user12031933
user12031933

Reputation:

If you have only the labels mentionned, you can use the @Stefan solution.

If you want to set all controls of the same type, you can use that:

private void ButtonAction_Click(object sender, EventArgs e)
{
  SetLabelsVisibility(this, false, true);
}

private void SetLabelsVisibility(Control control, bool state, bool recurse = false)
{
  if ( !recurse )
    Controls.OfType<Label>().ToList().ForEach(c => c.Visible = state);
  else
    foreach ( Control item in control.Controls )
    {
      if ( item is Label )
        item.Visible = state;
      else
      if ( item.Controls.Count > 0 )
        ToggleLabelsVisibility(item, state, recurse);
    }
}

Using recursivity on the form or on any container will change the visibility of all inner labels (or any other type of control you want) as well as all in inner containers and so on.

To toggle the visibility you can use a conditional variable such as:

private bool IsSomePanelLabelsVisible = true;

// To initialize at startup if needed
SetLabelsVisibility(SomePanel, IsSomePanelLabelsVisible);

// To toggle labels
IsSomePanelLabelsVisible = !IsSomePanelLabelsVisible;
SetLabelsVisibility(SomePanel, IsSomePanelLabelsVisible);

You can simplify and take the code you need from what is above.

Upvotes: 1

Stefan
Stefan

Reputation: 17678

Alternatively, assuming the labels are grouped in a way:

Logical group them in methods:

//best of both worlds, a toggle and a setter.
public void SetLabelVisibility(bool visible)
{
    Label1.Visible = visible;
    Label2.Visible = visible;
    Label3.Visible = visible;
}
public void ToggleLabelVisibility()
{
    SetLabelVisibility(!Label1.Visible);
}

Bu alternatively, you can put them in a panel, and just toggle the panel's visibility.

see: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.panel?view=netcore-3.1

public void TogglePanelVisibility(Panel p)
{
    p.Visible = !p.Visible;
}

Upvotes: 0

Falco Alexander
Falco Alexander

Reputation: 3342

you mean simply invert:

void ToggleLabel(Label l)
{ 
    l.Visible = ! l.Visible ;
} 

Upvotes: 5

Related Questions