首页 > 解决方案 > WinForms:使用 c# 添加控件

问题描述

我是 c# 新手,我知道如何动态添加控件,但我不知道如何将该控件设置为this.[control_name]. 请注意,这里thisForm.

这可以用静态方法完成private System.Windows.Forms.[Control_type] [control-name];,但我将如何从方法中做到这一点,以便我以后可以声明this.[control-name] = [variable]

请注意,variable类似于new TextBox();

标签: c#visual-studiowinformscontrolsdesktop

解决方案


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;

推荐阅读