In my project I have a Settings form and a Main form.
I\'m trying to call the Main form\'s MasterReset function from the Setting form, but nothing happens.
The Master fo
This worked for me: In your Program class, declare a static instance of Main (The class, that is) called Form
. Then, at the beginning of the Main
method, use Form = new Main();
So now, when starting your app, use
Application.Run(Form);
public static Main Form;
static void Main() {
Form = new Main();
Application.Run(Form)
}
Now, calling a function from another form is simple.
Program.Form.MasterReset(); //Make sure MasterReset is a public void
There are multiple solutions possible. But the problem itself arise from the bad design. If you need something to be accessed by many, then why should it belong to someone? If, however, you want to inform something about anything, then use events.
Your mistake is what you are creating another instance of form1
, thus MasterReset
is operating with form, which is not even shown.
What you can do:
Make (as Ravshanjon suggest) a separate class to handle that MasterReset
(and maybe something else). But also add to it an event. form1
and form2
can both subscribe to it and whenever either of them call MasterReset
- both will react.
Create form dependency (as BRAHIM Kamel suggested): when you create form2
, then pass to it form1
instance (as constructor parameter or by setting public property), to be able to call public non-static methods of form1
.
As a quick, but relatively legimate solution, make this method static
:
private static Form1 _instance;
public Form1()
{
InitializeComponents();
_instance = this;
}
public static void MasterReset()
{
// alot of code
_instance.listView1.Clear();
// alot of code
}
this way you can call MasterReset
from any other form like this Form1.MasterReset()
. Disadvantage of this method is what you can not have more than one instance of form2
(which is more likely anyway).
Do you know what composition over inheritance is?
In the form where you have MasterReset
you should do something like this:
Llet's suppose that in your second form you have something like this, and let's suppose your "mainform" will be called "MasterForm".
public partial class Form1 : Form
{
private MasterForm _masterForm;
public Form1(MasterForm masterForm )
{
InitializeComponent();
_masterForm = masterForm;
}
}
Here's the code in your masterForm Class:
private void button2_Click(object sender, EventArgs e)
{
Form1 form1 = new Form1(this);
}
Here's in your form1:
private void btn_MasterReset_Click(object sender, EventArgs e)
{
_masterForm.MasterReset();
}
Hope this helps!
I understand your problem, you can declare your function as public static void(also listView1 and people should be static too). Then when you want to call to like this:
private void btn_MasterReset_Click(object sender, EventArgs e)
{
Main.MasterReset();
}