简体   繁体   English

在将表单控件添加到其他类的表单中时出现问题C#

[英]Issue adding form controls to form from another class c#

Hello I am creating a windows form application, I am trying to create and add a new Control in this case it is a Panel from a different class, however when I have created the Panel and added it to the form it doesn't appear? 您好,我正在创建一个Windows窗体应用程序,我试图创建并添加一个新的控件,在这种情况下,它是来自其他类的一个Panel,但是当我创建Panel并将其添加到窗体时,它没有出现吗? [NOTE: I can change the text of the form with F.text("Some text"); [注意:我可以使用F.text(“ Some text”);更改表单的文本; but F.Controls.Add(panel1); 但是F.Controls.Add(panel1); doesn't work]. 不起作用]。

Here is my code: 这是我的代码:

public static void Create(Form1 F)
    {
         //this works:
         F.Text = "DEFAULT TEXT";
         Panel test = new Panel();
         test.Dock = DockStyle.Fill;
         test.BackColor = System.Drawing.Color.Black;
         test.Show();
         //this does not:
         F.Controls.Add(test);
    }

If you are adding the control from other class, Locate the control using Control c = fr.Controls["controlname"]; 如果要从其他类添加控件,请使用Control c = fr.Controls [“ controlname”];找到该控件。

and then add it to the form that you want. 然后将其添加到所需的窗体。 F.controls.add(c); F.controls.add(C);

This works fine for me 这对我来说很好

    public Form1(){
 InitializeComponent();
            Create(this);

        }

        public static void Create(Form1 F)
        {
            //this works:
            F.Text = "DEFAULT TEXT";
            Panel test = new Panel();
            test.Dock = DockStyle.Fill;
            test.BackColor = Color.Blue;

            //test.Show(); this is irrelevant
            //this does not:
            F.Controls.Add(test);

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

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