简体   繁体   English

找到动态创建的控件并隐藏它

[英]find dynamically created control and hide it

Again, I was creating buttons dynamically based on this post and now I need to hide it accordingly.同样,我根据这篇文章动态创建按钮,现在我需要相应地隐藏它。 How do I find and hide the buttons.如何查找和隐藏按钮。 This is new to me because I'm used to drag/drop and do stuff with it.这对我来说是新的,因为我习惯于拖/放并用它做事。 Any help would be appreciated.任何帮助,将不胜感激。 Thanks in advanced.先谢谢了。

Using my example from your previous question, I added a "name" property:使用我之前问题中的示例,我添加了一个“名称”属性:

int lastX = 0;
for (int i = 0; i < 4; i++) {
  Button b = new Button();
  b.Name = "button" + i.ToString();
  b.Location = new Point(lastX, 0);
  this.Controls.Add(b);
  lastX += b.Width;
}

Now you can access it by name:现在您可以按名称访问它:

if (this.Controls.ContainsKey("button1"))
  this.Controls["button1"].Visible = false;
var button = (from b in this.Controls.OfType<Button>()
              where b.Name == nameOfButton).First();

button.Hide();

you must know the name of your control.您必须知道控件的名称。 And then use this:然后使用这个:

foreach(Control control in Controls){
  if (control.Name == "your control name"){
      control.Visible = false;
  }
}

if your controls are in a panel named mypanel, for example, you must write foreach(Control control in mypanel.Controls) Hope it helps例如,如果您的控件在名为 mypanel 的面板中,则必须编写foreach(Control control in mypanel.Controls)希望foreach(Control control in mypanel.Controls)帮助

If you keep your dynamically created controls in a Dictionary<string, ControlType> , you can find them pretty easily and efficiently.如果您将动态创建的控件保存在Dictionary<string, ControlType> ,您可以轻松高效地找到它们。 The key would be your control name, of course.当然,关键是您的控件名称。

If your form contains panels etc. containers, you should do a recursive search:如果您的表单包含面板等容器,您应该进行递归搜索:

void SetVisible(Control c)
{
    if (control.Name == "your control name") 
          control.Visible = false; 

    foreach(Control control in c.Controls){       
      SetVisible(control);       
    }

} 

And then somewhere call:然后某处调用:

SetVisible(this);

Really old question, but the accepted answer didn't work for me because my controls were nested (children of another control).真的很老的问题,但接受的答案对我不起作用,因为我的控件是嵌套的(另一个控件的子项)。

The Controls.Find method worked for me with passing in 'true' for the second parameter which tells it to search children: Controls.Find 方法为我工作,为第二个参数传递“true”,告诉它搜索子项:

        Control c = panelControls.Controls.Find("MyControlName", true).FirstOrDefault();
        if (c != null && c is ComboBox) {
            ComboBox cmb = (ComboBox)c;
            cmb.Hide();
        }

Documentation: https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.control.controlcollection.find文档: https : //docs.microsoft.com/en-us/dotnet/api/system.windows.forms.control.controlcollection.find

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

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