Refresh a form after making edits on second [duplicate]

孤街浪徒 提交于 2019-12-02 14:08:51

Create an own event on form2 that triggers when the button gets clicked. This way you can just form2.OnUpdateClicked += yourMethod. Like this:

public partial class Form1 : Form
{
    private void CreateForm2()
    {
        Form2 frm2 = new Form2();
        // Hook the event of form2 to a method
        frm2.PropertyUpdated += Form2Updated;
    }

    private void Form2Updated(object sender, EventArgs e)
    {
        // this will be fired
    }
}

public partial class Form2 : Form
{
    // On form2 create an event
    public event EventHandler PropertyUpdated;

    private void Form2UpdateButton_Click()
    {
        // If not null (e.g. it is hooked somewhere -> raise the event
        if(PropertyUpdated != null)
            PropertyUpdated(this, null);
    }
}

Recommendations:

Your second form should be created with a reference to first one, ie,

Form1:

public void RefreshParameters()
{
  // ... do your update magic here
}

private void openForm2(..)
{
   // Pass your current form instance (this) to new form2
   var aForm = new Form2(this);
   aForm.Show(); // show, run, I don't remember... you have it
}

Form2:

// Here you will store a reference to your form1
form1 daddy = null;

// A new constructor overloading default one to pass form1
public Fomr2(Form1 frm):base()
{
  daddy = frm; // Here you store a reference to form1!
}

public void UpdateDaddy()
{
  // And here you can call any public function on form1!
  frm.RefreshParameters();
}

One way is to pass a reference of Form1 to Form2, like this:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void buttonLaunchForm_Click(object sender, EventArgs e)
    {
        Form2 form2 = new Form2();
        form2.LauncherForm = this;

        form2.Show();
    }

    public void RefreshFormData()
    {
         // Refresh
    }
}

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    public Form1 LauncherForm { set; get; }

    private void buttonUpdate_Click(object sender, EventArgs e)
    {
        // do your normal work then:

        LauncherForm.RefreshFormData();
    }
}

The above technique is called "Property-Injection";

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!