Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
512 views
in Technique[技术] by (71.8m points)

c# - Cannot access a disposed object?

I have a countdown Timer form - on the first form the user will enter the countdown time - warning times, end message, etc. There are also two Radio buttons (Max/Min) and depending on which is selected they will open a new Max or Min form where the time will actually start to countdown. It is working fine and counting down as I expect. However, if I exit the Max or Min form and try to run again with new times I get the error. The code is below - note the comment out ShowDialog(this); was something I tried - it let me close and open the new forms ok but it did not actually start the countdown. UpdateLabels is the function that does the updating of Labels.

                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 anyone help me out - I can post the UpdateLabels function if needed. I am pretty new to UI C# development so any help would be great. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is, that a closed form can not be used anymore (be reopened). Thats why the code you posted tries to stop closing and only hides your window. But for doing 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 closing it this way, show it with the Show() method.

However this is probably only a workaround and you could solve the problem with another design. Maybe it would be wise, to create a new instance of your form, every time you need it, instead of trying to reopen it every time. This also has the advantage that the form only requesires resources if it is really needed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...