Calling a method from another form

I am trying to call a method on my parent form from a child form, which in turn calls a method on my custom control. I can call if I do ...

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);
}

      

Finally, a method in 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 that the button is not being created in the addNode () method. If I call the method on the main form's onLoad event, it builds just fine. I was working in debug mode and I can see that the method gets called and the correct parameters are passed.

So why would it create a button when called from the parent but not when called from the child?

+3


source to share


2 answers


One way to do this is to pass frmMain

the Form.Show () method to your instance :

// ... 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 in your child code you can revert the Form.Owner property back to type frmMain

and do something with it

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

      

+3


source


In general, if you create a form in a method call and don't do something with it like storing it in an instance variable or Show (), then you are making a mistake. This form is never visible to the user and just gets garbage collected after your method exits.

Also you change the same button in basically the same way and add it to the same form multiple times. Do not do this. Learn about link semantics .



If you want your child form to be able to call something on the parent form, you could provide the parents with a reference to themselves for the child. It would be better to provide the parent with a delegate to the child that the child can call when needed.

+1


source







All Articles