将值设置为另一个表单中的对象

时间:2015-03-10 12:55:02

标签: c#

我正在使用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 个答案:

答案 0 :(得分:0)

试试这个

在Form2中:

public Form _parent;

public Form2(Form Parent)
    {
        InitializeComponent();

        this._parent = Parent;
    }

private void button1_Click(object sender, EventArgs e)
    {
        this._parent.textBox1.Text = "prova";

    }

在Form1中:

private void button1_Click(object sender, EventArgs e)
    {
        Form2 f = new Form2(this);
        f.Show();
    }

答案 1 :(得分:0)

请注意,在Form2中的“button1_Click”中,您正在创建一个“Form1”的新实例,因此Form2并不真正“知道”已经打开的Form1,

您应该将此对象引用(Form1)传递给Form2, 类似于Marcio的解决方案,但不是passong继承类“Form”,你应该传递“Form1”

在Form2中:

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

}

在Form1中:

private void button1_Click(object sender, EventArgs e)
{
    Form2 f = new Form2(this);   //<- "this" is the reference for the current "Form1" object
    f.Show();
}