在向表单动态添加控件时,只会显示一个控件

Jon*_*onE 6 c# winforms

我在运行时动态添加两个控件,但只显示第一个控件.

这是代码:

Label tempLab = new Label();
tempLab.text = "Test Label";
MyControl.Controls.Add(tempLab);
tempLab.Location = new Point(5,5);

Button tempBut = newButton()
tempBut.text = "Test Button";
MyControl.Controls.Add(tempBut);
tempBut.Location = new Point(20,20);
Run Code Online (Sandbox Code Playgroud)

不是copypasta所以忽略带帽的语法错误. 有任何想法吗 ?

它们被添加到组框中.我已经尝试将它们添加到面板或只是表单,并出现相同的问题.我不需要事件处理程序,所以请不要引用该要求.

Lar*_*rry 8

我很快尝试将代码粘贴到Windows窗体构造函数中.它运行正常,但由于它的大小,标签略微重叠按钮.您可能想要自动调整它:

Label tempLab = new Label();
tempLab.Text = "Test Label";
tempLab.AutoSize = true;
Controls.Add(tempLab);
tempLab.Location = new Point(5,5);

Button tempBut = new Button();
tempBut.Text = "Test Button";
Controls.Add(tempBut);
tempBut.Location = new Point(20,20);
Run Code Online (Sandbox Code Playgroud)

哦,顺便说一下.您提到您使用MyControl作为Panel或GroupBox.请确保您还将MyControl添加到Controls集合中.