Search code examples
c#formspartial-classes

How to get a method on a main form to get executed on the main form whenever i do some action on a secondary form?


I'm trying to update my data on a main form whenever I change some option in a secondary form.

Possible solution:

Make the method public on Form1 (the main form) like this:

public void updatedata()
{
//data update
}

And then call it on the secondary form:

Form1.updatedata()

This doesn't work and I believe it's because he is trying to update the Form2

I'm using partial classes, but I'm not very well versed on them.

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

And the secondary one:

 public partial class formOpConfig : Form
{
   private Form1 Opener { get; set; }



    public formOpConfig(Form1 opener)
    { //initialize component
    }
}

Solution

  • I feel like surely there is a duplicate question to match this one. But I have been unable to find it.

    Given the code you posted, your attempt probably would have worked had you used Opener.updatedata() instead of Form1.updatedata(). But that still would not have been the best solution.

    Commenter John Saunders is correct, the right way to do this is to declare an event in formOpConfig, and then have Form1 subscribe to it. That looks more like this:

    public partial class formOpConfig : Form
    {
        public event EventHandler UpdateData;
    
        private void SomethingHappens()
        {
            // do stuff...
            OnUpdateData();
            // maybe do other stuff too...
        }
    
        private void OnUpdateData()
        {
            EventHandler handler = UpdateData;
    
            if (handler != null)
            {
                handler(this, EventArgs.Empty);
            }
        }
    }
    

    The above declares an event, and raises that event (invokes the handlers) at the appropriate time (i.e. when SomethingHappens()).

    public partial class Form1 : Form
    {
        private void OpenConfigForm()
        {
            OpenConfigForm opConfig = new formOpConfig();
    
            opConfig.UpdateData += (sender, e) => updatedata();
        }
    
        // Note that this method is private...no one else should need to call it
        private void updatedata()
        {
            //data update
        }
    }
    

    Here, Form1 subscribes to the event when it creates the instance of formOpConfig (I am assuming Form1 is what creates that instance), and when its handler is invoked, it calls the updatedata() method you've already written.

    In this way, the two classes remain decoupled; i.e. they are not actually dependent on each other, more than they need to be (in particular, the formOpConfig class doesn't need to know anything about Form1).