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 form's Masterreset function looks like this.
public void MasterReset()
{
DialogResult dialogResult = MessageBox.Show("Are you sure you want to perform master reset? All settings will be set to default.", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (dialogResult == DialogResult.Yes)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string phonebook_path = path + "\\Phonebook\\Contacts.xml";
XmlDocument xDoc = new XmlDocument();
xDoc.Load(phonebook_path);
XmlNode xNode = xDoc.SelectSingleNode("People");
xNode.InnerXml = "";
xDoc.Save(phonebook_path);
listView1.Clear();
people.Clear();
}
else if (dialogResult == DialogResult.No)
{
return;
}
}
And I'm accessing it from the Settings form like this
private void btn_MasterReset_Click(object sender, EventArgs e)
{
Main f1 = new Main();
f1.MasterReset();
}
Why am I not seeing any results?
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".
Here's the code in your masterForm Class:
Here's in your form1:
Hope this helps!
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
, thusMasterReset
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
andform2
can both subscribe to it and whenever either of them callMasterReset
- both will react.Create form dependency (as BRAHIM Kamel suggested): when you create
form2
, then pass to itform1
instance (as constructor parameter or by setting public property), to be able to call public non-static methods ofform1
.As a quick, but relatively legimate solution, make this method
static
:this way you can call
MasterReset
from any other form like thisForm1.MasterReset()
. Disadvantage of this method is what you can not have more than one instance ofform2
(which is more likely anyway).This worked for me: In you Program class declare a static instance of Main (The class, that is.) called
Form
. Then, at the beginning of theMain
method, useForm = new Main();
So now, when starting you app, useApplication.Run(Form);
Now calling a function from another form is simple.
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: