Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call function from another form

Tags:

c#

void

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?

like image 310
Exinta Enea Avatar asked Nov 29 '13 12:11

Exinta Enea


People also ask

How call a function from another form in VB net?

You'd call Main. Main() or just Main() .


1 Answers

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!

like image 93
BRAHIM Kamel Avatar answered Sep 20 '22 08:09

BRAHIM Kamel