Home > Mobile >  Is there a way to call a function of an already existing form in Visual Studio with C#
Is there a way to call a function of an already existing form in Visual Studio with C#

Time:11-27

Is there a way I can call a function that is present in the parent form (users), where an instance of a second form(addNewUser) is called? What I want to do is when the second form closes, to execute a function in the parent form (users) which is updating a table so that the changes done in the second one (addNewUser) are updated in the table in the first form (users).

a simple drawing of what I am trying to achieve

CodePudding user response:

With an event driven paradigm like WinForms the best path is to use the events when there is one that you can intercept.
You can subscribe to an event from any class that creates instances of the event raiser. In this case you could simply bind an event handler to the FormClosed event raised by the second form.

// Suppose you have a button click that opens the second form.
private void button_Click(object sender, EventArgs e)
{
    SecondForm f = new SecondForm();
    f.FormClosed  = onSecondFormClosed;
    f.ShowDialog();
}

private void onSecondFormClosed(object sender, FormClosedEventArgs e)
{
    // Do whatever you need to do when the second form closes
}

CodePudding user response:

Define global variables to identify your instances of your forms:

internal static Form1 CurrentForm1 { get; set; }
internal static Form2 Frm2 { get; set; }

Then affect the variables as follows:

  public Form1()
    {
        InitializeComponent();
        CurrentForm1 = this;
    }

Somewhere in your code, you'll define the Form2:

Frm2 = new Form2();

Now, from the Frm2 code, you'll access to the form1 non static methods with:

Form1.CurrentForm1.UpdateMyThings();

And from the Frm1 code, you'll be able to watch the things on Frm2, like:

bool notified = false;
while (Frm2.backgroundWorker1.IsBusy)
{
    if (notified == false)
    {
        Message("Please wait...");
        notified = true;
    }
    Application.DoEvents();
}

In this example, Frm1 checks if the backgroundworker #1 is still running in Frm2 (The Message function may display the message in a label or something).

  • Related