tags:

views:

43

answers:

4

I have one form that has an option to open another (dialogue). I want an event to fire when the second window closes. The first form is named frmMain() the other is frmAddEmployee(). Heres what I have: in frmMain()

//create and open the second window
public void (object sender, EventArgs e)
{
     frmAddEmployee addEmp = new frmAddEmployee();
     addEmp.ShowDialogue();
}

//create event to handle addEmp being closed
public void addEmp_Closing(object sender, EventArgs e)
{
     PopulateEmployeeList();
}

I'm not sure the event is being recognized as an event. What am I doing wrong?

+1  A: 

There is Closing and Closed events which you can register for on the Form. You are registered for neither, unless your registration is taking place somehwere else?

Aaron
+4  A: 

Events in C# have to be registered manually - the C# compiler will not automatically register method as an event handler based just on the name of the method. You need:

 frmAddEmployee addEmp = new frmAddEmployee(); 
 addEmp.Closing += addEmp_Closing; // Register event handler explicitly
 addEmp.ShowDialogue(); 

Automatic registration of events is done in ASP.NET and Visual Basic has Handles clause, but in C#, you need to use the += operator to specify that some method should be called when an event occurs.

Tomas Petricek
+1 Beat me to it!
Andrew Barber
-1 I beat him to it...teez on the -1 :)
Aaron
@Aaron : I tried to smack you with a -1 for being a smarty, but I accidentally hit +1 instead! :P
Andrew Barber
@Andrew I'll take what I can get :D
Aaron
aha, thanks. Maybe its vs 2010, but the actual property was addEmp.FormClosing. Just a side thought though. This isn't going to add that register that event as a new event every time the window is opened, is it?
Sinaesthetic
@Sineasthetic, you are creating a new instance each time, so it will register the event handler for each instance. Also, see my answer - if you want to use ShowDialog, you don't need the event handler.
adrift
A: 

Before you call addEmp.ShowDialog() you need to set your method to handle the Closing event:

frmAddEmployee addEmp = new frmAddEmployee();
addEmp.Closing += addEmp_Closing;
addEmp.ShowDialogue();
Andrew Barber
+2  A: 

Assuming ShowDialogue means ShowDialog, then it shows the form modally and you don't need an event handler:

//create and open the second window
public void (object sender, EventArgs e)
{
     frmAddEmployee addEmp = new frmAddEmployee();
     addEmp.ShowDialog();
     PopulateEmployeeList();
}

If you don't show the second form modally, then you can hook up the event handler before showing the form like this:

public void (object sender, EventArgs e)
{
     frmAddEmployee addEmp = new frmAddEmployee();
     addEmp.FormClosed += AddEmpClosed;
     addEmp.Show();
}

private void AddEmpClosed(object sender, FormClosedEventArgs e)
{
     PopluateEmployeeList();
}
adrift