来自另一种形式的方法调用 [英] 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...
子形式:
private void btnSaveNode_Click(object sender, EventArgs e)
{
frmMain frm = new frmMain();
frm.getNodeData(txtPartName.Text);
this.Hide();
}
父级:
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;
}
所以我的问题是,按钮没有在addNode()方法中构建.如果我在主窗体的onLoad事件中调用该方法,则它的构建就很好.我在调试模式下运行,可以看到该方法被调用并且正确的参数正在传递.
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?
推荐答案
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);
// ...
}
这篇关于来自另一种形式的方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!