Can't access the remote object?

I have a countdown timer form - in the first form the user enters a countdown time - warning time, end message, etc. There are also two Radio buttons (Max / Min), and depending on the selected value, they will open a new Max or Min form, where the time will actually begin the countdown. It works fine and calculates as I expect. However, if I exit the Max or Min form and try to run again with new moments, I get an error. Code below - pay attention to the comment .ShowDialog (this); there was something that I tried - it allowed me to close and open new forms, but in fact this is not the beginning of the countdown. UpdateLabels is a feature that updates shortcuts.

bool Max = rbMax.Checked; if (Max == true) { //_Max.ShowDialog(this); _Max.Show(); } else //_Min.ShowDialog(this); _Min.Show(); UpdateLabels(); } 

I also tried the following, which I read online as a possible solution, but it also did not work.

  private void Max_FormClosing(object sender, FormClosingEventArgs e) { this.Hide(); this.Parent = null; } 

Can someone help me - I can post the UpdateLabels function if necessary. I am new to C # UI development, so any help would be great. Thanks.

+4
source share
4 answers

The problem is that the closed form can no longer be used (renewed). This is why the code you posted tries to stop closing and only hides your window. But for this, the Cancel-property must be set to true:

 private void Max_FormClosing(object sender, FormClosingEventArgs e) { this.Hide(); this.Parent = null; e.Cancel=true; } 

To show the form after it is closed, show it using the Show () method.

However, this is probably only a workaround, and you could solve the problem with a different design. It might be wise to create a new instance of your form every time you need it , rather than trying to reopen it every time. This also has the advantage that the form requires only resources, if it is really necessary.

+3
source

What you can do is add the following check before calling. Show method:

 if(_Max == null || _Max.IsDisposed) _Max = new MaxForm(); _Max.Show(); 

and similarly for the Min form

+4
source

Whenever a form is closed, all its resources are freed . This means that you can no longer access the object, since it no longer exists - it has been freed and deleted from memory. To avoid this, you can undo the closing of the form and hide it (which will become transparent to the user).

 this.Hide(); e.Cancel=true; 

The updated version of your code is as follows:

 private void Max_FormClosing(object sender, FormClosingEventArgs e) { e.Cancel = true; this.Hide(); this.Parent = null; } 
+1
source

A simple solution that instantiates an object of the called form in a button click event, for example.

 private void buttonSetting_Click( object sender, EventArgs e ) { ***_setting = new SettingWindow();*** //When I need to show the settings window _setting.Show(); } 
0
source

All Articles