Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How to close a form and show another form if the progress of background worker reaches 100%..Form is showing but the form supposed to close isn't closing...
C#
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        Stopwatch sw = Stopwatch.StartNew();

        sw.Stop();
        var elapsedMs = sw.ElapsedMilliseconds;
        int sp = int.Parse(sw.ElapsedMilliseconds.ToString());
        // Your background task goes here
        for (int i = 0; i <= 100; i++)
        {
            // Report progress to 'UI' thread
            backgroundWorker1.ReportProgress(i);
            // Simulate long task
            System.Threading.Thread.Sleep(100);
        }
    }

   void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            // The progress percentage is a property of e
            progressBar1.Value = e.ProgressPercentage;
            if (progressBar1.Value == 100)
            {
                Form1 fm1 = new Form1();
                fm1.Close();
                Form2 fm = new Form2();
                fm.Show();
            }
        }

ALso tried under
C#
private void myBGWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("Done");
            Form1 fm1 = new Form1();
            fm1.Close();
            Form2 fm = new Form2();
            fm.Show();
        }
Posted
Updated 28-Apr-13 0:52am
v3

1 solution

No, no - it doesn't work like that.
You don't want to create a new instance of the current form and try to close it, you want to "close" the current instance, and show a new form. Unfortunately, that will probably kill you application as well.

So, your choices are:
1) Create a "master" form which is never shown, and which displays Form1 until teh job is doen, then closes it and shows teh second form.
2) Hide the current form, and close it when the second form shuts.
The second is easier to show you:
C#
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
   {
   // The progress percentage is a property of e
   progressBar1.Value = e.ProgressPercentage;
   if (progressBar1.Value == 100) 
      {
      Hide();
      Form2 fm = new Form2();
      fm.ShowDialog();
      Close();
      }
   }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900