简体   繁体   English

C#中的事件和Windows窗体

[英]Events and windows forms in C#

So I just read through the Events tutorial on MSDN and am having some problems applying it in my program. 因此,我只是通读了MSDN上的“事件”教程,在将其应用到我的程序时遇到了一些问题。 I was wondering if someone here could give me a hand. 我想知道这里有人可以帮忙吗?

So I have two forms, a parent called frmInventory and a child called frmNewProduct . 因此,我有两种形式,一种称为frmInventory的父级, frmInventory一种称为frmNewProduct的子frmNewProduct The child has a button called btnAccept . 这个孩子有一个名为btnAccept的按钮。 Currently, there is a single subscriber called btnAccept_Click subscribed to this event. 当前,有一个名为btnAccept_Click订阅者订阅了此事件。 The existing subscriber is on the child form. 现有订户位于子窗体上。 I want to add a second subscriber to this event, but this subscriber will be on the parent form. 我想向该事件添加第二个订阅者,但是该订阅者将位于父表单上。 Here is the function on my parent form: 这是我父母表格上的函数:

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

And here is my attempt to subscribe the function to my child's event: 这是我尝试将该功能预订给我孩子的活动:

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

As I stated in one of your previous posts, I think ShowDialog() would be better, for example: 正如我在您以前的一篇文章中所述,我认为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 your parent form.. ..以您的父母形式..

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

您应该在子表单的构造函数中包含以下代码!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM