具有变量名称的面板控件 [英] Panel control with variable name

查看:131
本文介绍了具有变量名称的面板控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有25个面板控件(可见错误). 我想让它可见.

I have 25 panel control (Visible false). I want to make it visible.

但是它不起作用: (错误1'字符串'不包含'可见'的定义,找不到扩展方法'可见'接受类型为'字符串'的第一个参数(您是否缺少using指令或程序集引用?) )

But it doesn' work: (Error 1 'string' does not contain a definition for 'Visible' and no extension method 'Visible' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) )

for (int i = 0; i < 25; i++)
{
    string panelID = "panel" + i.ToString();
    panelID.Visible = true;
}

帮助

推荐答案

您的代码在很多方面都是错误的.

Your code is wrong in so many fronts.

实际上,您正在做的是创建25个具有值panel0panel1panel2等的字符串,并尝试将值分配给它的属性.但是字符串不包含名为Visible的属性,因此显然您会得到一个错误.

As it is, what you're doing is creating 25 strings with values panel0, panel1, panel2 etc., and trying to assign a value to a property of it. But strings don't contain a property named Visible, so obviously you'll get an error.

您要执行的操作是在表单中获取类型为Panel的控件,并设置其值.

What you want to do is get hold of controls of type Panel in your form, and set their values.

foreach(var panel in this.Controls.OfType<Panel>())
{
    panel.Visible = true;
}

注意事项:上面的内容仅会以您最上方的形式找到Panel控件.如果有嵌套的控件,则可能需要编写一种方法来递归地找到它们.以上只是为了给您一个想法.

Caveat: the above will only find Panel controls in your topmost form. If there are controls that are nested, you'd want to perhaps write a method to recursively find them. Above is just to give you the idea.

此外,如果您有多个Panel控件,并且只想设置符合您的命名约定的面板名称的属性,则可以将其过滤掉.

In addition, if you have multiple Panel controls and if you only want to set the property of those panels names fit your naming convention you can filter them out.

foreach(var panel in this.Controls.OfType<Panel>())
{
    if( panel name fits your naming convention)
        panel.Visible = true;
}

在这里,您可以使用Regex,使用自定义功能等来查找正确的面板名称.

Here, you can look for correct panel name by using a Regex, use a custom function etc.

这篇关于具有变量名称的面板控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆