从其他类c#附加控件到表单

时间:2016-03-20 15:41:11

标签: winforms c#-4.0 controls

在C#win表单中 - 我想从其他类添加控件到表单。

我该怎么做?

我试图将表单作为形式参数传递给另一个类中的函数,但是如何将它附加到表单?

class Class1
{
    System.Windows.Forms.TextBox txt = new System.Windows.Forms.TextBox();  
}

另外,我有Form1.cs

我想将txt添加到Form1。

另外,我想从Class1设置txt的属性,但它失败了..

谢谢!

1 个答案:

答案 0 :(得分:1)

这应该有效:

class Class1
{
    System.Windows.Forms.TextBox txt = new System.Windows.Forms.TextBox();

    public void AddTextBoxToForm(Form form)
    {
        form.Controls.Add(txt);
        txt.Text = "Hello World! I've been added to a form.";
    }  
}

您还可以设置Location的{​​{1}}和Size等属性。请注意,将TextBox添加到不同的表单中是一个坏主意。

如果您有任何错误,您的问题应该更具体地说明"失败"装置

通常,TextBox的所有控件都应该是Form的成员,而不是在其他类中定义。