Home > Net >  Creating a class that loops through textboxes and labels making them visible in winform
Creating a class that loops through textboxes and labels making them visible in winform

Time:12-05

I am very new to c# and visual studio.

I am using c# with Visual studio. I want to create a method that lops through a number of textboxes and labels and set their visible control to "True."

This is the code I have come up with so far, but it does not work.

public static void showFields(params string[] values)
{
    foreach (var value in values)
    {
        value.Visible = true;
    }

}

Any help would be greatly appreciated.

CodePudding user response:

You are on the right path, just need to replace string with Control, by the way, string does not have the Visible property.

public static void showFields(params Control[] values)
{
      foreach (var value in values)
      {
        value.Visible = true;
      }
}

CodePudding user response:

Code should be similar to this. You may have nested controls. In this case, you create a recursive method

private void MakeThemVisible(Control topControl)
{
    foreach (var c in topControl.Controls)
    {

        if (c is TextBox txt && <your second criteria>) // <-- pattern matching
        {
            // <---- txt specific code here -------
            txt.Visible = true;
            continue;
        }
        else if (c is Label lbl && <your second criteria>) // <-- pattern matching
        {
            // <---- lbl specific code here -------
            
            lbl.Visible = true;
            continue;
        }
    
        MakeThemVisible(c);
    }
}

Your form is also control

If you already have a list of needed controls in the form of array - Control[] values, you can use LINQ

values.ToList().ForEach(c => {c.Visible = true;});
  • Related