【问题标题】:How to pass the value from child form to parent form?如何将值从子表单传递到父表单?
【发布时间】:2016-07-15 21:07:34
【问题描述】:

我有 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.exe 中出现“System.InvalidCastException”类型的未处理异常
附加信息:无法将“BillingForm.MDIParent”类型的对象转换为“BillingForm.BillingForm”

【问题讨论】:

  • @itsme86 我看到了那个编码。我只使用了相同的编码。但我得到了例外。请看我的错误信息
  • BillingForm 是 MDI 表单吗?
  • @itsme86 MDIParent 是 MDI 表单。BillingForm 是 MDI 表单的子表单之一。在 MDI 表单中按 ctrl+N 会打开 BillingForm
  • BillingForm bf=(BillingForm)this.Owner;这一行放一个断点并调试。当代码中断时,将鼠标高亮显示在Owner 上并查看它的类型。从那里,查看Owner 上是否有任何属性将返回您正在寻找的BillingForm

标签: c# forms


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-12
    • 2019-09-07
    • 2018-04-05
    • 1970-01-01
    相关资源
    最近更新 更多