Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

form not showing

Tags:

c#

winforms

Perhaps this has something to do with it being the mainForm, but I'll ask the question. I have my mainForm that is the first to load when the program is booted.

I then click a button called Add, which should open a new form, and close the mainForm.

The problem is, is shows the new form for a split second, then closes both.

The code:

private void addFrmBtn_Click(object sender, EventArgs e)
{
    saveForm saveform = new saveForm();
    saveform.Show();
    this.Close();
}
like image 264
sark9012 Avatar asked Apr 19 '10 12:04

sark9012


2 Answers

In your Program.Main() method, you probably have something like this:

class Program
{
    void Main()
    {
        Application.Run(new MainForm());
    }
}

This means your application's message loop is running around the main form. Once that closes, the application's main UI thread goes with it.

You can either:

  • Change your Program.Main() method so that this doesn't happen (there are overloads to Application.Run().
  • Change the Shutdown Mode in the project properties (strictly speaking only in VB.NET, but you can do a similar thing in C#. See http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/61b817f8-d7d3-44de-9095-91a6e3f2150c for details).
  • Hide MainForm rather than closing it.

Here's how you do option 3:

private void addFrmBtn_Click(object sender, EventArgs e)
{
    saveForm saveform = new saveForm();
    saveform.Show();
    this.Hide();
}
like image 62
Neil Barnwell Avatar answered Nov 03 '22 01:11

Neil Barnwell


The problem seems, is you are closing the parent form which opened the child form. To retain the form use this.Hide(); instead of close.

like image 38
anantmf Avatar answered Nov 03 '22 00:11

anantmf