Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

.NET 2

// dynamic textbox adding
myTextBox = new TextBox();
this.Controls.Add(myTextBox);

// ... some code, finally

// dynamic textbox removing
myTextBox.Dispose();

// this.Controls.Remove(myTextBox); ?? is this needed

Little explanation

  • Surely, if I Dispose a control I will not see it anymore, but anyway, will remain a "Nothing" in the parent controls collection?
  • need I also, like MSDN recommends, remove all handlers from the control?
See Question&Answers more detail:os

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

1 Answer

No, you don't.
I tried it.

You can paste the following code into LINQPad:

var form = new Form();
var b = new Button();
form.Controls.Add(b);
b.Click += delegate { b.Dispose(); };
Application.Run(form);

EDIT: The control will be removed from the form's Controls collection. To demonstrate this, replace the click handler with the following:

b.Click += delegate { b.Dispose(); MessageBox.Show(form.Controls.Count.ToString());};

It will show 0.

2nd EDIT: Control.Dispose(bool disposing) contains the following code:

                if (parent != null) { 
                    parent.Controls.Remove(this); 
                }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...