skip to Main Content

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.

2

Answers


  1. 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;});
    
    Login or Signup to reply.
  2. 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;
          }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search