Reputation: 2719
I have created multiple user controls in my project and what I need to do is to be able to switch between them on a panel control.
for example, if the user click button1, userControl1 will be added to panel after removing every control on it and so on.
I have this code :
panel1.Controls.Add(MyProject.Modules.Masters);
but it's not working.
How I can do it?
Upvotes: 14
Views: 73491
Reputation: 1
Isn't just 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());
Upvotes: 0
Reputation: 950
You need to instantiate a new MyProject.Modules.Masters.
MyProject.Modules.Masters myMasters = new MyProject.Modules.Masters()
panel1.Controls.Add(myMasters);
This will only add a new control to panel1. If you also want to clear everything out of the panel before adding the control like you said in the question, call this first:
panel1.Controls.Clear();
Upvotes: 12
Reputation: 67075
You have to instantiate your controls. You will have to make sure the size is set appropriately, or for it to have an appropriate dockfill.
var myControl = new MyProject.Modules.Masters();
panel1.Controls.Add(myControl);
Upvotes: 27