2012-07-31 82 views
0

因此,我刚刚阅读了MSDN上的事件教程,并在我的程序中应用它时遇到了一些问题。我想知道这里有人能否帮我一把。C#中的事件和Windows窗体#

所以我有两种形式,一种叫做frmInventory的父母和一个叫frmNewProduct的孩子。孩子有一个叫做btnAccept的按钮。目前,订阅此事件的单个订户名为btnAccept_Click。现有用户在子表单上。我想为此活动添加第二位订阅者,但此订阅者将位于父表单上。这里是我的父窗体上的功能:

public void updateInventoryFromChild(object sender, EventArgs e) 
{ 
    //Not sure how to get this working either, but that is another story 
    _inventroy = (frmNewProduct)sender._inventory 
} 

这里是我的尝试订阅功能,以我孩子的事件:

this.btnAccept.Click += new System.EventHandler((frmInventory)this.Parent.updateInventoryFromChild); 
+0

你想要在父窗体上触发点击事件吗? – 2012-07-31 03:26:59

+0

我希望在子窗体上单击某个特定按钮时触发该事件。在父表单上触发什么意思?我认为答案是肯定的。 – Nick 2012-07-31 03:33:28

+0

你有什么问题?你有错误吗?事件是否在父窗体上触发?另外,你如何用Show()或ShowDialog()打开子窗体? – 2012-07-31 03:39:44

回答

3

正如我在以前的帖子中的一个说,我想的ShowDialog()会更好,例如:

class ChildForm : Form { 
    private Inventory _inventory; 

    public Inventory MyInventory { 
     get { 
      return _inventory; 
     } 
    } 

    private void btnAccept_Click(object sender, EventArgs e) { 
     _inventory = <set_inventory_here>; 
     DialogResult = System.Windows.Forms.DialogResult.OK; 
    } 
} 

..in你父窗体..

public void updateInventoryFromChild(object sender, EventArgs e) 
{ 
    ChildForm childForm = new ChildForm(); 
    if (childForm.ShowDialog() == System.Windows.Forms.DialogResult.OK) { 
     _inventory = childForm.MyInventory; 
    } 
} 
1

你应该在子窗体的构造函数下面的代码!

this.btnAccept.Click += new System.EventHandler(this.Parent.updateInventoryFromChild); 
+0

现在,我在InitializeComponent函数中对所有Forms进行标准化处理。这是不够的吗? – Nick 2012-07-31 03:46:38

+0

@ user1556487你应该在调用InitializeComponent之后做到这一点! – Anirudha 2012-07-31 03:52:31