【问题标题】:Adding controls to a different form将控件添加到不同的表单
【发布时间】:2015-01-10 09:21:29
【问题描述】:

我有几个表单,我希望能够为某个表单添加一个按钮,无论代码在哪里。

通常我会执行this.Controls.Add(button) 之类的操作,但我不希望将其添加到该表单中。我尝试过类似Form1 frm = new Form1()frm.Controls.Add(button) 的操作,但这也不起作用。需要怎么写?

此代码不起作用,表单仍为空白

Button b = new Button();
b.Size = new Size(50,50);
b.Location = new Point(50,50);
new Form1().Controls.Add(b);

没有错误,但没有添加任何内容。

我找到了一种解决方法。

Control ctrl = this;
ctrl.Controls.Add(b);

这行得通,但我宁愿有一种方法来准确指定将其添加到哪个表单

【问题讨论】:

  • Didn't work 不是问题描述。请更具体,并为您的问题添加更多详细信息。
  • 没有添加任何内容,表单只是空白
  • 贴一小段代码说明问题。

标签: c# forms controls


【解决方案1】:
Button b = new Button();
b.Size = new Size(50,50);
b.Location = new Point(50,50);
new Form1().Controls.Add(b); // This will do nothing you want.

将控件添加到表单会将其添加到运行它的单个实例中,而不是一般的表单中。

试试这个:

Form1 form = new Form1();
Button b = new Button();
...
form.Controls.Add(b);
form.ShowDialog(); // Or .Show()

Form1 anotherForm = new Form1();
anotherForm.ShowDialog(); // This instance will NOT have the added button

如果您是从其他表单执行此操作,您也可以尝试以下操作:

// Constructor
this._otherForm = new Form1(); // save reference of the other form, to be able to add controls to it later

// Anywhere in the code
this._otherForm.Show(); // will display the other form

// On user action, for example on button click
this._otherForm.Controls.Add(c); // will add the control c to the other form

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-27
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多