简体   繁体   中英

Referencing objects using a variable (c#)

I've been doing a program which needs to change object attributes during the execution. In order for me to have a easy management I've kept the original object name ie "button1"

My question is if there is a way to reference object names by variables to be changed with a loop

I've had to be writing stuff like

private void disable ()
{
    this.button1.Visible = false;
    this.button2.Visible = false;
    this.button3.Visible = false;
    //...
}

I've tried something like

int a;
for(a=1;a==50;a++)
{
    this.buttona.Visible =false;
}

which obviously did not work

Then is there a way I can refer object with a variable?

Thanks in Advance

You can use this code:

        foreach (var c in this.Controls)
        {
            if (c is Button button)
                button.Visible = false;
        }

Or this one:

        for (int i = 0; i < 50; i++)
        {
            var c = this.Controls["button" + i];
            (c as Button).Visible = false;
        }

This MIGHT NOT work if you are not doing UWP, WPF, etc. If you are doing UWP, WPF, etc, this might help. Since all of these buttons belong to one panel (I assume so) the children or content of the panel should be an IEnumerable object, which can be processed by foreach loops. For example, if I have the following XAML code:

<Grid x:Name="myGrid">
    <Button x:Name="Button1" Tag="myButton1"/>
    <Button x:Name="Button2" Tag="myButton2"/>
    <!-- ... -->
</Grid>

I can iterate through the buttons using this:

foreach(Button button in myGrid.Children){
    if(!button.Tag.StartsWith("myButton")) continue;
    button.Visibility = Visibility.Collapsed;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM