Dynamically Created User Controls In C#

THE DOCTOR picture THE DOCTOR · Feb 23, 2009 · Viewed 10.4k times · Source

I am working in a C# winforms project and I have a user control which gets loaded upon its selection from a tool-strip menu. I have a dictionary lookup set to occur upon form load of the user control for other functionality. Also, when I close the user control I am just using the ".Hide();" method. I noticed that when I load the user control the first time everything is fine, but when I close it and choose to open it again the 2nd time it creates a new instance of the object thus throwing off my dictionary lookup. Therefore, I wrote some code in an attempt to fix the issue.

What I need to do is to somehow say that if an instance of the user control already exists, do not create a new instance of that object. Instead, just make the user control visible again. Therefore I have written code in an attempt to accomplish this purpose. When I select the item the first time, everything is fine. When I hide the user control and try to re-open it again nothing happens.

The following is the code I have written for this purpose which occurs upon the selection of the item from the tool-strip menu:

      if (Controls.ContainsKey("CheckAvailUserControl"))
       {
           Controls["CheckAvailUserControl"].Dock = DockStyle.Fill;
           Controls["CheckAvailUserControl"].Visible = true;
           Controls["CheckAvailUserControl"].Show();
           Controls["CheckAvailUserControl"].Refresh();
       }

       else
       {
          UserControl checkAvailUserControlLoad = new CheckAvailUserControl();
          Controls.Add(checkAvailUserControlLoad);
          checkAvailUserControlLoad.Dock = DockStyle.Fill;
          checkAvailUserControlLoad.Visible = true;
          checkAvailUserControlLoad.Show();
       }

When I trace through my code in the debugger it is in fact hitting the right parts of the above if/else statement. Its just not displaying the user control on the screen the 2nd time I attempt to load it.

The question is: How do I get the user control to load correctly after I close it, then select it from the tool-strip menu again?

Answer

Daniel LeCheminant picture Daniel LeCheminant · Feb 23, 2009

I think that Controls.ContainsKey(...) is always returning false, because you never assigned a name to your control when you created it.

If, when you create the control, you say

//...
checkAvailUserControlLoad.Name = "Something"
//...
Controls.Add(checkAvailUserControlLoad);

then

Controls.ContainsKey("Something") 

will return true, and you'll be able to re-use the control by using Controls["Something"]