C# closing a form on button Click

c#, winforms

Solution

`ShowDialog` will block until that dialog is closed, so you can't do what you want in the calling class. What I would do is pass the `this` pointer to `newDB` constructor, remember it there temporarily as a `Form`, and in the `Load` function of `newDB`, call `Close` on the passed in `Window/Form`, thus accomplishing what you want.

If you pass it as a `Form` parameter, `DB` will not have to 'know' about the exact concrete class name you are calling from, but you will still be able to call `Close` on it.

Does that help?

Problem

I am trying close the form after button1_Click, I tried using this.Close() in several spots, but it is not working. I want the button click to open a new Form called newDB. But when using this.Close() it will only close the form and not open up my new form. Is there any other way of doing this so that I can close the first form and still open up the newDB form? ``` private void button1_Click(object sender, EventArgs e) { try { conn = new SqlCeConnection(@"Data Source=|DataDirectory|\Baseball.sdf; Persist Security Info=False;"); DB newDB = new DB(); newDB.ShowDialog(); this.Close(); } catch (Exception error) { MessageBox.Show("Could not connect to database!\n" + error, "Database Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } // this.Close(); } ```

Original source