如何将值从子窗体传递到父窗体

本文关键字:窗体 | 更新日期: 2023-09-27 17:57:24

我有2个表单,分别称为BillingForm(父表单)和SearchProduct(子表单)。

帐单表单代码

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

搜索产品表单代码(子窗体)

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 中发生了类型为"System.InvalidCastException"的未处理异常.exe
其他信息:无法将类型为"BillingForm.MDIParent"的对象强制转换为类型"BillingForm.BillingForm

如何将值从子窗体传递到父窗体

尝试将父级传递到构造函数中并在变量中使用它

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