Calling Function on other Form C#

  • Thread starter Thread starter Ed West
  • Start date Start date
E

Ed West

Hello

I open a new form and do some stuff, and when I am done I want to call a
function on the original form... how can i do this? Do I need to send
in the calling form as a reference or something? if so, how exactly do
i do this? thanks.

**Form1:**
public void UpdateSchedule()
{
// do stuff
}

private void mnuSchedule_Click(object sender, System.EventArgs e)
{
frmSchedule fSchedule = new frmSchedule();
fSchedule.ShowDialog();
}

**frmSchedule:**
private void btnSave_Click(object sender, System.EventArgs e)
{
// do some stuff
frmSchedule.UpdateSchedule();
Close();
}
 
Try passing in an instance of the calling form to the called form through an
overloaded constructor

Form1 _callingForm = null;

public frmSchedule(Form1 callingForm)
{
this._callingForm = callingForm
}


/////***************inside form1******************

private void mnuSchedule_Click(object sender, System.EventArgs e)
{
frmSchedule fSchedule = new frmSchedule(this);
fSchedule.ShowDialog();
}
 
awesome, thanks.

Try passing in an instance of the calling form to the called form through an
overloaded constructor

Form1 _callingForm = null;

public frmSchedule(Form1 callingForm)
{
this._callingForm = callingForm
}


/////***************inside form1******************

private void mnuSchedule_Click(object sender, System.EventArgs e)
{
frmSchedule fSchedule = new frmSchedule(this);
fSchedule.ShowDialog();
}
 
Its better to:

1. Define a property on the form that you can "get" when the form closes (if
the form provides data to the calling form), or

2. Have an event on the form that the calling form can subscribe to (if it
has to perform an action)

If you *have* to provide an instance of the form, consider using an
interface to define the interaction between the two forms, rather than
providing the form itself.

These solutions reduce coupling between components in your program.

The example that was given will work however!

Just a thought.

Ta

Paul Wardle
 
Back
Top