问题描述
我是 C# 新手,我知道如何动态添加控件,但我不知道如何将该控件设置为 this.[control_name]
。请注意,这里的 this
是 Form
。
这可以用 private System.Windows.Forms.[Control_type] [control-name];
静态完成,但是我如何从一个方法中做到这一点,以便我以后可以声明 this.[control-name] = [variable]
?
请注意,variable
类似于 new TextBox()
;
解决方法
var txt = new TextBox(); //txt is the variable you are looking for
Form1.Controls.Add(txt); //added it to the form
现在您可以通过txt
访问它:
txt.Location = new Point(0,0);
txt.Visible = true;
如果您在方法中创建控件(如您在评论中提到的),您可以返回并使用它,如下所示:
public TextBox AddTextBox()
{
var txt = new TextBox();
Form1.Controls.Add(txt);
return txt;
}
var newTxt = AddTextBox();
newTxt.Location = new Point(0,0);
newTxt.Visible = true;