Change the Visible property on several elements at once

38 Views Asked by At

In this code I have several elements like text box and buttons, and on depend the case, some are visible and some are not, like this (there are more elements):

txtTipCOP.Visible = true;
lblIngreseCantidad.Visible = true;
lblEquivale.Visible = true;
txtTCDolar.Visible = false;
txtTCEuro.Visible = false;
btnCantidadInicio.Visible = false;
btnEquivaleInicio.Visible = false;
txtCantidad.Visible = false;
txtEquivalen.Visible = false;                    

I want to optimize the code, but I don't know how to control several Visible properties with 1 true, is this possible?

Thank you for your time.

I am changing every Visible property individually but I think it's not the optimal way?

2

There are 2 best solutions below

2
Caleb On

If you're looking to set all these controls to Visible = true, you could create a foreach loop. Modify the following to your needs.

foreach (Control control in Page.Controls)
{
        if (control is TextBox || control is Label) // whatever controls you want
        {
            control.Visible = false;
        }
}

However in terms of performance, it will be negligible because its performing the same operation if you set them all individually. Personally I would go with ever is more maintainable.

1
Enigmativity On

Trivially you could do this:

txtTipCOP.Visible = 
lblIngreseCantidad.Visible =
lblEquivale.Visible = true;
        
txtTCDolar.Visible = 
txtTCEuro.Visible =
btnCantidadInicio.Visible =
btnEquivaleInicio.Visible =
txtCantidad.Visible = 
txtEquivalen.Visible = false;

A better approach might be this:

Control[] controls = new Control[]
{
    txtTipCOP,
    lblIngreseCantidad,
    lblEquivale,
    txtTCDolar,
    txtTCEuro,
    btnCantidadInicio,
    btnEquivaleInicio,
    txtCantidad,
    txtEquivalen,
};

controls.Take(3).ForEach(c => c.Visible = true);
controls.Skip(3).ForEach(c => c.Visible = false);

Or:

foreach (Control control in controls.Take(3))
    control.Visible = true;

foreach (Control control in controls.Skip(3))
    control.Visible = false;

If you don't have the .ForEach extension method you can use .ToList().ForEach instead.