在C#win表单中 - 我想从其他类添加控件到表单。
我该怎么做?
我试图将表单作为形式参数传递给另一个类中的函数,但是如何将它附加到表单?
class Class1
{
System.Windows.Forms.TextBox txt = new System.Windows.Forms.TextBox();
}
另外,我有Form1.cs
我想将txt添加到Form1。
另外,我想从Class1设置txt的属性,但它失败了..
谢谢!
答案 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
的成员,而不是在其他类中定义。