【问题标题】:WinForms: adding a control with c#WinForms:使用 c# 添加控件
【发布时间】:2021-07-06 03:57:31
【问题描述】:

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

这可以使用private System.Windows.Forms.[Control_type] [control-name]; 静态完成,但我将如何通过方法执行此操作,以便稍后声明this.[control-name] = [variable]

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

【问题讨论】:

  • 我这样做是因为我需要能够从创建控件的另一个范围引用该控件。所以我会使用this.[control-name],因为这在所有范围内都是通用的。
  • 你不能这样做,因为代码不会编译
  • 您可以拥有一个以名称为键的控件字典
  • @stuartd 那么我会使用Form.Controls.Find([dict],true)[0],我假设?

标签: c# visual-studio winforms controls desktop


【解决方案1】:
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;

如果您在方法中创建控件(正如您在 cmets 中提到的),您可以返回并使用它,如下所示:

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;

【讨论】:

  • 但是,如果我在方法内部执行代码的第一部分,然后在该方法外部执行第二部分,则会出现引用错误。我如何能够在创建它的方法之外引用这个文本框?谢谢。
  • 在你希望访问的范围内声明变量,例如在表单类中的函数之外。
  • 啊,是的,行得通!谢谢你。我还必须使用字典,在每个控件名称的末尾添加一个数字,这样每个名称都是唯一的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-10
相关资源
最近更新 更多