form1 字符串不传递给 form2

form1 string is don't pass to form2

想要使 form1 pubId 值从 form2 更改。 pubId 总是 get null 没变。我该如何解决这个问题?

Form1代码:

public string pubId = string.Empty;

public void button1_Click(object sender, EventArgs e)
{
    try
    {
        form2 _frm2 = new form2();
        _frm2 .FormClosed += _frm2_FormClosed;
    }
    catch (Exception ex)
    {
        MessageBox.show(ex);
    }
}

private void _frm2_FormClosed(object sender, FormClosedEventArgs e)
{
    if (pubId == "8")
    {
       MessageBox.show("works");
    }
}

Form2代码:

public void buttonsend_Click(object sender, EventArgs e)
{      
    idfrm2 = "8";

    form1 _frm1 = new form1 ();                                          
    _frm1.pubId = _idfrm2;

    this.Close();
}

在这一行中,您使用新的空 pubId 创建一个新表单。

form1 _frm1 = new form1 ();   

只需为form2创建一个构造函数来传递它。 例如:

private string _pubId;
public form2(string pubId)
{
    _pubId = pubId;
}

然后就可以使用了:

form2 _frm2 = new form2(pubId);

您可以在 Form1 维护的控件列表中维护对 Form2 的引用,并按如下方式访问它:

Form1代码:

 public partial class Form1 : Form
{
    Form2 localfrm2;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {


            Form2 frm2 = new Form2();
            frm2.FormClosed += Frm2_FormClosed;

        localfrm2 = frm2;
            frm2.Show();

    }

    private void Frm2_FormClosed(object sender, FormClosedEventArgs e)
    {
        MessageBox.Show(localfrm2.PubId);
    }
}

Form 2 :

  public partial class Form2 : Form
{
    public string PubId { get; set; }

    public Form2()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        PubId = textBox1.Text;
    }
}

如果这解决了您的问题,请点赞