将“值”设置为另一个窗体中的对象
本文关键字:窗体 对象 另一个 设置 | 更新日期: 2024-11-08 07:25:53
我正在用C#开发一个WindowsFormProject,其中带有以下代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.Show();
}
}
}
这是 Form1 的代码;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
f1.textBox1.Text = "prova";
f1.Refresh();
}
}
}
结束这是 Form2 的代码。
目标是在表单 1 的文本框中编写文本,我将访问修饰符设置为公共,但不起作用
有什么解决办法吗?
试试这个
在窗体 2 中:
public Form _parent;
public Form2(Form Parent)
{
InitializeComponent();
this._parent = Parent;
}
private void button1_Click(object sender, EventArgs e)
{
this._parent.textBox1.Text = "prova";
}
在窗体 1 中:
private void button1_Click(object sender, EventArgs e)
{
Form2 f = new Form2(this);
f.Show();
}
请注意,在 Form2 的"button1_Click"中,您正在创建"Form1"的新实例,因此 Form2 不会真正"知道"已全部打开的 Form1,
应将此对象引用 (Form1) 传递给 Form2,类似于 Marcio 的解决方案,但不是传递继承类 "Form",而应该传递 "Form1"
在窗体 2 中:
public Form1 _parent;
public Form2(Form1 parent) //<-- parent is the reference for the first form ("Form1" object)
{
InitializeComponent();
this._parent = parent;
}
private void button1_Click(object sender, EventArgs e)
{
this._parent.textBox1.Text = "prova"; // you won't get an exception here because _parant is from type Form1 and not Form
}
在窗体 1 中:
private void button1_Click(object sender, EventArgs e)
{
Form2 f = new Form2(this); //<- "this" is the reference for the current "Form1" object
f.Show();
}