微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

WinForms:使用 c# 添加控件

如何解决WinForms:使用 c# 添加控件

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

这可以用 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;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。