【问题标题】:Set Value to object from another Form将值设置为来自另一个表单的对象
【发布时间】:2015-03-10 12:55:02
【问题描述】:

我正在使用 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的文本框中写一段文字,我把访问修饰符设置为public,但是不起作用

有什么办法吗?

【问题讨论】:

标签: c#


【解决方案1】:

试试这个

在 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";

    }

在表格 1 中:

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

【讨论】:

  • 我有这个错误:错误 1 ​​'System.Windows.Forms.Form' 不包含 'textBox1' 的定义并且没有扩展方法 'textBox1' 接受类型为 'System.Windows 的第一个参数.Forms.Form' 可以找到(您是否缺少 using 指令或程序集引用?) c:\users\cristian\documents\visual studio 2013\Projects\WindowsFormsApplication2\WindowsFormsApplication2\Form2.cs 24 26 WindowsFormsApplication2
【解决方案2】:

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

您应该将此对象引用 (Form1) 传递给 Form2, 类似于 Marcio 的解决方案,但不是传递继承类“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

}

在表格 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();
}

【讨论】:

    猜你喜欢
    • 2014-07-08
    • 1970-01-01
    • 2020-12-07
    • 2022-12-10
    • 1970-01-01
    • 2020-08-31
    • 1970-01-01
    • 2013-02-25
    • 2020-07-29
    相关资源
    最近更新 更多