我有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;
}
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”
最佳答案
尝试将父级传递给构造函数并在变量中使用它
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();
}
}
关于c# - 如何将值从子窗体传递到父窗体?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38405030/