I have one form that opens another form upon clicking a button. When the new form opens, I have a progress bar complete via a loop, then I want the form to close. Here is the button click event that launches the new form.
private void calculateButton_Click(object sender, EventArgs e)
{
if (checkFormComplete())
{
ProgressForm proForm = new ProgressForm();
proForm.Show();
}
}
And here is the code for the new form that completes a progress bar that should then close itself.
public ProgressForm()
{
InitializeComponent();
for (int i = 0; i < 101; i++)
calculationProgress.Value = i;
this.Close();
}
However, upon running this I get:
Cannot access a disposed object. Object name: 'ProgressForm'.
And the debugger points to this line of my main form:
proForm.Show();
I'm not sure I understand why, or what the proper way to do this is. How is that line being called after the close statement inside my new form?
The form is trying to close itself before it's even shown (because you have your code in the constructor). Put your progress bar code and Close() call in the FormLoad or FormShown event instead. Example:
private void ProgressForm_Shown(object sender, EventArgs e)
{
for (int i = 0; i < 101; i++)
{
calculationProgress.Value = i;
Application.DoEvents(); // force the form to update itself
}
this.Close();
}
Allow the loading to complete before you try to close the form :-)
You should start your progress bar loop in the Form_Load event.
However note that looping like that will cause your form to lock up until the progress bar completes rendering.
Do the progress loop in a background thread. A BackgroundWorker is ideal for running the progress loop.
public proForm()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
}
proForm_Load()
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
(int i = 0; i < 101; i++) worker.ReportProgress(i);
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
resultLabel.Text = (e.ProgressPercentage.ToString() + "%");
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.Close();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With