简体   繁体   中英

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. 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 . The child has a button called btnAccept . Currently, there is a single subscriber called btnAccept_Click subscribed to this event. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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