How to add a user control to a panel

I created several controls in my project, and I need to do this to switch between them in the control panel.

for example, if the user presses button1, userControl1 will be added to the panel after deleting each control, etc.

I have this code:

panel1.Controls.Add(MyProject.Modules.Masters); 

but it does not work.

How can i do this?

+7
source share
3 answers

You need to create an instance of your controls. You will need to make sure that the size is set appropriately or that there is an appropriate dock for it.

 var myControl = new MyProject.Modules.Masters(); panel1.Controls.Add(myControl); 
+17
source

You need to create an instance of the new MyProject.Modules.Masters.

 MyProject.Modules.Masters myMasters = new MyProject.Modules.Masters() panel1.Controls.Add(myMasters); 

This will add a new control to panel 1. If you also want to clear everything from the panel before adding the control, as you said in the question, first call this:

 panel1.Controls.Clear(); 
+9
source

Not easier.

 panel1.Controls.Clear(); panel1.Controls.Add(new MyProject.Modules.Masters()); 

EDIT: Maybe try this ...

 panel1.Controls.Cast<Control>().ForEach(i => i.Dispose()); panel1.Controls.Clear(); panel1.Controls.Add(new MyProject.Modules.Masters()); 
0
source

All Articles