简体   繁体   中英

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

If you keep your dynamically created controls in a Dictionary<string, ControlType> , you can find them pretty easily and efficiently. 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:

        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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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