Home > Mobile >  Trying to call a method from another form
Trying to call a method from another form

Time:03-05

I have two forms, the first of which has a datagrid view on it and the second is a data entry form. I have created a method that refreshes the datagrid view on the first form but I want to call it when i close form number two. I quickly found that i cant call the method on the first form from the second form so I googled and found that when i open the second form i need to initialise it by using form1(this); however when i do this i get an error message:

'Form1' does not contain a contructor that takes 1 arguments

Does anyone know why this isnt working as i copied this from someone elses solution? Also what do i then need to put in my second form to be able to call the method in the first form?

private void button2_Click(object sender, EventArgs e)
        {
            //Open New Record Form
                      
            Form1 form1 = new Form1(this);
            form1.Show();
        }

CodePudding user response:

'Form1' does not contain a contructor that takes 1 arguments

Then give it a constructor which takes that argument. For example:

public class Form1 : Form
{
    private Form2 _form2;

    public Form1(Form2 form2)
    {
        _form2 = form2;
    }

    // the rest of the class
}

The idea here is that if any given instance of Form1 needs an instance of Form2 to do its work, then it should require that instance on its constructor. (You could even add some error checking in the constructor to make sure the passed instance isn't null for example.) Then any time something creates an instance of Form1, it will need to supply that dependency.

Then any operation within Form1 will have access to that dependency in the _form2 field.

CodePudding user response:

I have created a method that refreshes the datagrid view on the first form but I want to call it when i close form number two.

What you can do is make Form1 update ITSELF when Form2 closes. You'd wire up the FormClosed event of Form2 when you create and display it:

// ... this is in FORM1 !!! ...
private void btnShowForm2_Click(object sender, EventArgs e)
{                 
    Form2 f2 = new Form2();
    f2.FormClosed  = (s2, e2) => this.Update(); // <-- change to your "update" method name
    f2.Show();
}

CodePudding user response:

private void button2_Click(object sender, EventArgs e){
 this.Hide();
 var form = new Form1();
 form.Closed  = (s, args) => this.Close();
 form.Show();
}
  •  Tags:  
  • c#
  • Related