简体   繁体   中英

How to pass the value from child form to parent form?

I have 2 forms called BillingForm (parent form) and SearchProduct (child form).

BillingForm code

private void textBoxProductNo_KeyDown(object sender, KeyEventArgs e)
{
    if(e.KeyCode==Keys.F9)
    {
        using(SearchProduct sp=new SearchProduct)
        {
            sp.ShowDialog(this);
        }
    }
}

public void updatedText(string fromChildForm)
{
     textBoxProduct.text=fromChildForm;
}

SearchProduct form code (Child Form)

private void dataGridView1_KeyDown(object sender,KeyEventArgs e)
{
    if(e.KeyCode==Keys.Enter)
    {
        BillingForm bf=(BillingForm)this.Owner;   //Error appear here 
        bf.updatedText("Hello World");
        this.close();
    }
}

I am getting an error message.

An unhandled exception of type 'System.InvalidCastException' occurred in BillingSoftware.exe
Additional information: Unable to cast object of type 'BillingForm.MDIParent' to type 'BillingForm.BillingForm

Try to pass the parent into constructor and use it in a variable

using(SearchProduct sp = new SearchProduct(this))
{
    sp.ShowDialog(this);
}

//In SearchProduct class
public BillingForm MyParent {get; private set;}

public SearchProduct(BillingForm parent)
{
    this.MyParent = parent;
}

private void dataGridView1_KeyDown(object sender,KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        BillingForm bf = this.MyParent;
        bf.updatedText("Hello World");
        this.close();
    }
}

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