Sandro Milhano
Sandro Milhano

Reputation: 17

When form load, open form 2 and close form 1

When the program loads I want to check for a file, if the file exists I want to continue, if it doesn't I want it to not open the main form and open a form 2.

This is what I have so far:

private void Home_Load(object sender, EventArgs e)
{
    string path = @"c:\Path\Path2\file.txt";
    if (!File.Exists(path))
    {
        MessageBox.Show("File not found!");
        form2 f = new form2();
        f.Show();
        this.Hide();
    }

    else
    {
        MessageBox.Show("File found!");
    }
}

But it opens the two forms. Can anyone please help me? Thanks.

Upvotes: 1

Views: 2307

Answers (1)

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

Seems to me you should do this in the application start. Right now you're doing this in the load of the first form, that you don't want open. So, something like this:

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    string path = @"c:\Path\Path2\file.txt";
    if (!File.Exists(path))
    {
        Application.Run(new form2());
    }
    else
    {
        Application.Run(new form1());
    }
}

Upvotes: 3

Related Questions