TextBox可见属性

时间:2013-02-17 07:00:44

标签: c#

我目前正在使用文本框上的可见属性。下面我复制粘贴了我的代码片段。我的表单中有几个文本框。尝试编写它将变得非常乏味,就像我在下面的所有文本框一样。有没有办法将我的代码压缩到几行以使文本框可见?

    public void makeVisible()
    {
        textBox1.Visible = true;
        textBox2.Visible = true;
        textBox3.Visible = true;
        textBox4.Visible = true;
        //etc.

    }

3 个答案:

答案 0 :(得分:2)

试试这个:

foreach(Control c in Controls)
{
 TextBox tb = c as TextBox;
 if (tb !=null) tb.Visible = false; //or true, whatever.
}

对于有限的文本框:

int count = 0;  
int txtBoxVisible = 4;  
foreach(Control c in Controls)
{
    if(count <= txtBoxVisible)
    {
        TextBox tb = c as TextBox;
        if (tb !=null) tb.Visible = false; //or true, whatever.
        count++;
    }
}

您可以根据需要设置txtBoxVisible

答案 1 :(得分:1)

将文本框放在数组中并循环遍历数组或

将文本框放在面板,网格,组......中,并更改该容器的可见性。

答案 2 :(得分:1)

使用类似于以下的内容:

foreach (TextBox textBox in container.Controls.Cast<Control>().OfType<TextBox>())
{
    textBox.Visible = value;
}

请参阅以下内容:

LINQ (Language-Integrated Query)

Enumerable.Cast Method

Enumerable.OfType Method