简体   繁体   English

如何在C#中将UserControl动态添加到窗体

[英]How to dynamically add UserControl to a Form in C#

I am new to C#. 我是C#的新手。 I have Form1 and Form2 and UserControl1 . 我有Form1Form2UserControl1 I want to dynamically add the UserControl1 to Form2 and show Form2 using ShowDialog but Form2 is shown empty. 我想将UserControl1动态添加到Form2并使用ShowDialog显示Form2Form2显示为空。 I know I can add UserControl1 to Form2 using Form2 constructor but I want to do it form Form1 . 我知道我可以使用Form2构造函数将UserControl1添加到Form2但是我想从Form1

Anyone knows how to do it? 有人知道该怎么做吗?

This code is in Form1: 这段代码在Form1中:

UserControl1 _UserControl1 = new UserControl1();

using (Form2 _Form2= new Form2 ())
 {

 _Form2.Controls.Add(_UserControl1);

 _Form2.ShowDialog();
  // Form2 is shown empty
 }

When creating controls at runtime, make sure the new control has all the necessary properties set. 在运行时创建控件时,请确保新控件已设置了所有必需的属性。 Location and Size are important, the control may be drawing off the form, or be tiny. 位置大小很重要,控件可能正在绘制表格,或者很小。

Also, make sure the control is not being hidden by another control. 此外,请确保该控件未被其他控件隐藏。 Make sure the Visible property is set true, and that there are no panels or other controls in the area that was specified for the control to be. 确保将Visible属性设置为true,并且在为该控件指定的区域中没有面板或其他控件。

If there are other controls on the form, you can try setting the control's z-index using _Form2.Controls.SetChildIndex(_UserControl,0); 如果表单上还有其他控件,则可以尝试使用_Form2.Controls.SetChildIndex(_UserControl,0);设置控件的z-index Alternatively, if the control is intended to be on a panel, add the control to the panel's Controls collection. 或者,如果要将控件放在面板上,请将控件添加到面板的“控件”集合中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM