My Winform application has 3 form: MainForm, Form1 and Form2. MainForm has an UserControl; when application starts, it calls MainForm, MainForm will be loaded and added Form1 onto UserControl:
private void MainForm_Load(object sender, EventArgs e)
{
Form1 frm = new Form1() { Dock = DockStyle.Fill, TopLevel = false, Visible = true };
xtraUserControl1.Controls.Add(frm);
}
On Form1, I use delegate:
public delegate void Tranferdata(string txt);
public Tranferdata _tranfer;
private void Gettxt(string txt)
{
tbx_Recieve.Text = txt;
}
Form1 has a button to call Form2:
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.ShowDialog(this);
}
Form2 will send value to Form1 after closed, Code on Form2:
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
using (Form1 frm1 = (Form1)this.Owner)
{
frm1._tranfer(tbx_Numb.Text);
}
}
private void button1_Click_1(object sender, EventArgs e)
{
this.Close();
}
But my code doesn't work correctly. It crashed at 'using (Form1 frm1 = (Form1)this.Owner)' and show the System.InvalidCastException. How can I fix this?
答案 0 :(得分:0)
它在该行崩溃的原因是因为您没有将Form1设置为Form2的所有者。
要修复,首先将Form1作为类变量而不是局部变量:
Form1 form1;
private void MainForm_Load(object sender, EventArgs e)
{
form1 = new Form1() { Dock = DockStyle.Fill, TopLevel = false, Visible = true };
xtraUserControl1.Controls.Add(form1);
}
然后您可以在创建时使用它来分配Form2的所有者:
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.Owner = form1;
frm2.ShowDialog(this);
}
而且,就像Ron Beyer在评论中提到的那样,考虑删除使用声明,它会关闭Form1,听起来不像你想做的那样。
现在,虽然这种方法有效,但您还应该考虑一些问题: 为什么你首先选择使用“所有者”属性?你真的需要它吗?将Form1作为Form2的所有者意味着Form2将在Form1关闭时关闭。由于您在Form2上使用ShowDialog,它将阻止用户在Form2显示时关闭Form1,因此它似乎不需要。 如果使用Owner属性的原因只是为了使用委托,那么你可能只是将Form2的属性添加到Form1类型中,这样就可以为你输入类型安全和优质代码。
但是有更好的方法:MainForm可以注册到Form2的Closed事件并在Form1上调用该方法。这将删除不需要的依赖项(Form2和Form1根本不会彼此了解)使代码更健康。
答案 1 :(得分:0)
我找到了解决这个问题的方法: 在表格2中:
str = String.fromCString(UnsafePointer(chars)) // UTF-8 is implicit
// or:
str = String(CString: UnsafePointer(chars), encoding: NSUTF8StringEncoding)
并在事件调用form2中以表单1调用它:
public void SetParent(Form1 frm)
{
frm1 = frm;
}