如何将值从子表单传递给父表单?

时间:2016-07-15 21:07:34

标签: c# forms

我有两种名为 BillingForm (父表单)和 SearchProduct (子表单)的表单。

BillingForm代码

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表单代码(子表单)

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

我收到错误消息。

BillingSoftware.exe中发生未处理的“System.InvalidCastException”类型异常 附加信息:无法将“BillingForm.MDIParent”类型的对象强制转换为“BillingForm.BillingForm

1 个答案:

答案 0 :(得分:0)

尝试将父项传递给构造函数并在变量

中使用它
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();
    }
}