Israel Rodriguez
Israel Rodriguez

Reputation: 209

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

Upvotes: 0

Views: 6207

Answers (3)

m.zam
m.zam

Reputation: 467

Based on your comment to Mitch, this what you should do:

  1. In your parent form, create a static ListView object which point to you customer list

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

Upvotes: 0

BlakeH
BlakeH

Reputation: 3494

Based on your comments to Mitch, it sounds like you need to rebind data on your main form after you close the child form. This is a much better approach than closing/reopening the main form.

Upvotes: 1

Mitch
Mitch

Reputation: 22311

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:

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#.

Upvotes: 0

Related Questions