C# 如何将用户控件添加到面板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9763228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add user control to panel
提问by Saleh
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.
例如,如果用户单击 button1,则 userControl1 将在删除其上的每个控件后添加到面板等等。
I have this code :
我有这个代码:
panel1.Controls.Add(MyProject.Modules.Masters);
but it's not working.
但它不起作用。
How I can do it?
我该怎么做?
采纳答案by Justin Pihony
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);
回答by Fur Dworetzky
You need to instantiate a new MyProject.Modules.Masters.
您需要实例化一个新的 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 添加一个新控件。如果您还想在像问题中所说的那样添加控件之前清除面板中的所有内容,请先调用它:
panel1.Controls.Clear();
回答by ad48
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());

