I have one form that has an option to open another (dialogue)开发者_如何学Go. 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?
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.
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();
}
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?
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();
精彩评论