C# 如何将 UserControl 显示到表单中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12647473/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:00:21  来源:igfitidea点击:

How can I Display UserControl into a form

c#winforms

提问by Spoon Yukina

I have created a UserControl and I want when I click on some button to display this UserControl into my form.

我已经创建了一个 UserControl,当我点击某个按钮时,我想要在我的表单中显示这个 UserControl。

Is there any way to do that ?

有没有办法做到这一点?

采纳答案by Adam Plocher

You can dynamically add the user control to the forms Controls collection.

您可以将用户控件动态添加到表单控件集合中。

For example, in the button click event handler:

例如,在按钮单击事件处理程序中:

MyUserControl uc = new MyUserControl();
uc.Dock = DockStyle.Fill;
this.Controls.Add(uc);

回答by Steve Wellens

Put it on the form. Start it out invisible, when the button is clicked set it to visible.

把它放在表格上。开始时不可见,单击按钮时将其设置为可见。

回答by hamed

Drag your user control to your form and change it's Visible property to false

将您的用户控件拖到您的表单中并将其 Visible 属性更改为 false

UserControl1.Visible = false;

Then on your button set the Visibility of your usercontrol to true.

然后在您的按钮上将用户控件的可见性设置为 true。

private void button1_Click(object sender, EventArgs e)
{
    UserControl1.Visible = true;
}

回答by HOKBONG

Is it a typical ascx type of control? If yes then you can set the "visible" property of the control through the button click event.

它是典型的 ascx 类型的控件吗?如果是,那么您可以通过按钮单击事件设置控件的“可见”属性。

Let say you have :

假设你有:

<uc1:ft ID="userctrl"  runat="server" Visible="false" />

then on your button event:

然后在您的按钮事件上:

protected void Button1_Click(object sender, EventArgs e)
{
    userctrl.Visible = true;
}