Skip to main content
 首页 » 编程设计

c#之以编程方式将控件添加到另一个 Winform C# .NET

2024年02月13日13shangdawei

我现在有母表格,我想以编程方式创建一个新表格。我创建了新窗体,但无法向窗体添加控件。

private void CreateWindows() 
    { 
        newWindow = new Form(); 
        Application.Run(newWindow); 
 
        newWindow.Activate(); 
 
        newWindow.Size = new System.Drawing.Size(40, 40); 
 
       Label label1 = new Label(); 
 
       newWindow.Controls.Add(label1);   
 
       label1.Text = "HI"; 
       label1.Visible = true; 
       label1.Size = new System.Drawing.Size(24, 24); 
       label1.Location = new System.Drawing.Point(24, 24); 
 
    } 

我试过上面的代码,显示了新的表格,但我看不到label1。

感谢任何帮助。

请您参考如下方法:

尝试在设置标签属性后添加控件,然后显示新窗口。

private void CreateWindows() 
{ 
    newWindow = new Form(); 
 
    newWindow.Activate(); 
 
    newWindow.Size = new System.Drawing.Size(40, 40); 
 
   Label label1 = new Label(); 
 
 
   label1.Text = "HI"; 
   label1.Visible = true; 
   label1.Size = new System.Drawing.Size(24, 24); 
   label1.Location = new System.Drawing.Point(24, 24); 
 
   newWindow.Controls.Add(label1);   
   newWindow.Show(); 
   //use this if you want to wait for the form to be closed 
   //newWindow.ShowDialog(); 
 
}