简体   繁体   English

C#隐藏所有标签/控件

[英]C# Hide all labels/ controls

Is it possible within a windows form using C# to hide all specific controls upon form load, eg labels or buttons and then chose to show the ones that I wan't to be shown? 是否可以在Windows窗体中使用C#在窗体加载时隐藏所有特定控件,例如标签或按钮,然后选择显示我不想显示的控件?

I've got a program which contains a lot of buttons and labels but I only want one or two shown upon load and I feel doing this method of label1.Hide(); 我有一个包含很多按钮和标签的程序,但是我只想在加载时显示一个或两个,而我感觉使用的是label1.Hide();方法label1.Hide(); for every label seems inefficient but instead I could just show labels I want when I want. 每个标签似乎效率低下,但我可以只显示我想要的标签。 Maybe using a loop, something like this: 也许使用循环,如下所示:

foreach (Label)
{
    this.Hide();
}

It sounds like you could just hide them all in the designer, and then you wouldn't have to deal with hiding them at runtime. 听起来您可以将它们全部隐藏在设计器中,然后不必在运行时隐藏它们。

If you do have to hide them at runtime, then you can grab all controls on the Form of a certain type with a little LINQ: 如果必须在运行时隐藏它们,则可以使用一些LINQ来获取某种类型的Form上的所有控件:

foreach (var lbl in Controls.OfType<Label>())
    lbl.Hide();

You could even filter the controls based on their name, so you only hide the ones you want to hide: 您甚至可以根据控件的名称过滤控件,因此仅隐藏要隐藏的控件:

foreach (var lbl in Controls.OfType<Label>().Where(x => x.Name != "lblAlwaysShow"))
    lbl.Hide();

If they're also tucked inside of other controls, like Panels or GroupBoxes, you'll have to iterate through their ControlCollections too: 如果它们也隐藏在其他控件(如Panels或GroupBoxes)中,则也必须遍历其ControlCollections:

foreach (var lbl in panel1.Controls.OfType<Label>())
    lbl.Hide();

foreach (var lbl in groupBox1.Controls.OfType<Label>())
    lbl.Hide();

You can try this too with less code. 您也可以用更少的代码尝试一下。 It works another form controls (etc. Textbox, Button...) 它适用于其他表单控件(例如文本框,按钮...)

foreach (Control lbl in Controls)
{
 if ((lbl) is Label)
 {
  lbl.Hide();
 }
}

try this: 尝试这个:

 foreach(Label l in this.Controls.OfType<Label>())
 {
    l.Visible=false;
 }

 this.myControl.Visible=true;

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

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