问题
I am quite new to windows forms. I would like to know if it is possible to fire a method in form 1 on click of a button in form 2? My form 1 has a combobox. My form 2 has a Save button. What I would like to achieve is: When the user clicks on Save in form 2, I need to check if form 1 is open. If it is open, I want to get the instance and call the method that would repopulate the combo on form 1.
I would really appreciate if I get some pointers on how I can do work this out. If there any other better way than this, please do let me know.
Thanks :)
Added: Both form 1 and form 2 are independent of each other, and can be opened by the user in any order.
回答1:
You can get a list of all currently open forms in your application through the Application.OpenForms property. You can loop over that list to find Form1. Note though that (in theory) there can be more than one instance of Form1 (if your application can and has created more than one instance).
Sample:
foreach (Form form in Application.OpenForms)
{
if (form.GetType() == typeof(Form1))
{
((Form1)form).Close();
}
}
This code will call YourMethod
on all open instances of Form1.
(edited the code sample to be 2.0-compatible)
回答2:
Of course this is possible, all you need is a reference to Form1 and a public method on that class.
My suggestion is to pass the Form1 reference in the constructor of Form2.
回答3:
What you can do is create static event in another class and then get Form 1 to subscribe to the event. Then when button clicked in Form 2 then raise the event for Form 1 to pick up on.
You can have declare the event in Form 1 if you like.
public class Form1 : Form
{
public static event EventHandler MyEvent;
public Form1()
{
Form1.MyEvent += new EventHandler(MyEventMethod);
}
private void MyEventMethod(object sender, EventArgs e)
{
//do something here
}
public static void OnMyEvent(Form frm)
{
if (MyEvent != null)
MyEvent(frm, new EventArgs());
}
}
public class Form2 : Form
{
private void SaveButton(object sender, EventArgs e)
{
Form1.OnMyEvent(this);
}
}
来源:https://stackoverflow.com/questions/920006/firing-a-method-in-form-1-on-click-of-a-button-on-form2