Andrew Day
Andrew Day

Reputation: 125

Method call from another form

I am trying to call a method on my parent form from a child form, which in turn calls a method in my custom user control. I am able to make the call if I do this...

In child form:

private void btnSaveNode_Click(object sender, EventArgs e)
{
    frmMain frm = new frmMain();
    frm.getNodeData(txtPartName.Text);
    this.Hide();
}

In parent form:

public void getNodeData(string partNbr)
{
    string strPartNbr = partNbr;
    buildNode(strPartNbr);
}

public void buildNode(string partNbr)
{
    drewsTreeView tv = new drewsTreeView();
    tv.addNode(partNbr);
}

And finally, the method in the user control

public void addNode(string strPartNbr)
{
    btnNode.Location = new Point(13, 13);
    btnNode.Width = 200;
    btnNode.Height = 40;
    //btnNode.Text = strPartNbr;
    btnNode.Text = "Testing";
    this.Controls.Add(btnNode);
    btnNode.Click += btnNode_Click;
}

So my problem is, the button does not get built in the addNode() method. If I call the method in the onLoad event of the main form, it builds just fine. I ran in debug mode, and I can see the method is getting called and the correct parameters are getting passed.

So why will it build the button when called from the parent, but not when called from the child?

Upvotes: 4

Views: 2358

Answers (2)

Idle_Mind
Idle_Mind

Reputation: 39122

One way to do this is to pass in your instance of frmMain to the Form.Show() method:

// ... in frmMain, displaying the "child" form:
frmChild child = new frmChild(); // <-- whatever your child type is
child.Show(this); // passing in a reference to frmMain via "this"

Now over in your child form code, you can cast the Form.Owner property back to your frmMain type and do something with it:

private void btnSaveNode_Click(object sender, EventArgs e)
{
    frmMain frm = (frmMain)this.Owner;
    frm.getNodeData(txtPartName.Text);
    // ...
}

Upvotes: 4

Rikki Gibson
Rikki Gibson

Reputation: 4337

In general, if you instantiate a form in a method call and you don't do something with it like save it to an instance variable or Show() it then you're making a mistake. That form is never seen by the user and just gets garbage collected after your method exits.

Also, you are modifying the same button in basically the same way and adding it to the same form multiple times. Don't do this. Learn about reference semantics.

If you want your child form to be able to cause something to happen in the parent form, you could have the parent give a reference to itself to the child. It would be better to have the parent provide a delegate to the child that the child can invoke as needed.

Upvotes: 1

Related Questions