简体   繁体   English

C#Windows窗体应用程序,从子窗体关闭父窗体

[英]C# windows form application, closing parent form from child

I know this is going to sound a little confusing but here it goes. 我知道这听起来会有些混乱,但是确实如此。 So i have this parent form and when I click a button a new child form shows up(note that my parent form its still open). 所以我有这个父表单,当我单击一个按钮时,会出现一个新的子表单(请注意,我的父表单仍处于打开状态)。 What i want is when i press a button from my child form i want is a new parent form to show up and to close the parent form that was already opening from the beginning. 我想要的是当我从子窗体中按下按钮时想要的是一个新的父窗体来显示并关闭从一开始就已经打开的父窗体。 I hope this doesnt sound confusing. 我希望这不会让人感到困惑。 I try playing around with it but nothing seems to work I have something like this on my parent form 我尝试使用它,但是似乎没有任何效果,我的父母表格上有类似的内容

Form2 loging = new Form2();    
loging.ShowDialog();

on my child form 以我的孩子的形式

Form1 loging = new Form1();
loging.Close()
loging.ShowDialog();
this.Close();

Based on your comments to Mitch, it sounds like you need to rebind data on your main form after you close the child form. 根据您对Mitch的评论,听起来您需要在关闭子窗体后重新绑定主窗体上的数据。 This is a much better approach than closing/reopening the main form. 与关闭/重新打开主窗体相比,这是一种更好的方法。

In short, you cannot change a window's parent, and you cannot change whether a window is modal. 简而言之,您不能更改窗口的父级,也不能更改窗口是否为模式窗口。 Destroy the child, close the parent, open a new parent, show a new child. 销毁孩子,关闭父母,打开新父母,展示新孩子。 Alternatively, if the child window need not be modal, create the child with Form.Show() and then do something like the following in the child form: 另外,如果子窗口不需要是模式窗口,则使用Form.Show()创建子窗口,然后在子窗口中执行以下操作:

parentForm.Close();
Form newParent = new NewParentForm();
newParent.Show();
this.BringToFront();

MFC used to be able to fake being modal, but it did so by using a custom window procedure - not something particularly easy to do in C#. MFC曾经能够伪造模态,但是它是通过使用自定义窗口过程来伪造的-在C#中并非特别容易做到。

Based on your comment to Mitch, this what you should do: 根据您对Mitch的评论,您应该执行以下操作:

  1. In your parent form, create a static ListView object which point to you customer list 在您的父窗体中,创建一个指向您的客户列表的静态ListView对象

     public partial class Form1 : Form { public static ListView lsvCustomer; public Form1() { InitializeComponent(); // this will allow access from outside the form lsvCustomer = this.listView1; } private void button1_Click(object sender, EventArgs e) { frmInput f = new frmInput(); f.ShowDialog(this); } } 
  2. Then in your child form, you update the list directly from your child form as below : 然后在您的子表单中,直接从您的子表单中更新列表,如下所示:

     public partial class frmInput : Form { public frmInput() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //update user input to customer list in parent form Form1.lsvCustomer.Items.Add(textBox1.Text); } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM