繁体   English   中英

使用变量更改对象的属性? C#/ Visual Studio

[英]Changing The Property Of An Object Using Variables? C#/Visual Studio

好的,所以我有100个按钮,我需要根据while循环中的条件更改颜色。 它们被命名为button1,button2,button3等。 在循环的第一次(迭代?)期间,我需要编辑button1,下一次button2,第三次button3,依此类推。

我以为我可以制作一个等于“ button”的字符串,将循环数添加进去,然后像这样改变颜色。

String ButtonNumber = "button" + i; i =循环次数

当我尝试使用ButtonNumber.BackColor = Color.Red;编辑颜色时ButtonNumber.BackColor = Color.Red; 它不会让我,因为它没有将ButtonNumber视为一个按钮,而是一个字符串。 我该如何完成? 谢谢! (这是我第一次编程)

考虑使用Controls.Find按名称查找控件,然后可以更改其属性:

for (int i = 1; i <= 100; i++)
{
    var buttonName = string.Format("button{0}", i);

    var foundControl = Controls.Find(buttonName, true).FirstOrDefault();

    if (foundControl != null)
    {
        // You can now set any common control property using the found control
        foundControl.BackColor = Color.Red;

        // If you need to set button-specific properties (i.e. properties
        // that are not common to all controls), then cast it to a button:
        var buttonControl = foundControl as Button;

        if (buttonControl != null)
        {
            buttonControl.AutoEllipsis = true;
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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