David
David

Reputation: 5456

Remove TabPage: Dispose or Clear or both?

I am working on a windows form that has a TabControl named tabDocuments. I came across this piece of code that removes all pages from the TabControl.

for (int i = tabDocuments.TabPages.Count - 1; i > -1; i--) {
    tabDocuments.TabPages[i].Dispose();
}
    tabDocuments.TabPages.Clear();

The person who wrote this code has already left a while ago. I am trying to understand why the code is calling Clear() after disposing each of the tabPages (looks un-necessary to me). Can anyone please explain to me why? Or is calling Clear() extra?

Upvotes: 5

Views: 8771

Answers (3)

Philip Wallace
Philip Wallace

Reputation: 8035

This snippet is from Control.Dispose:

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

Therefore you just have to call Dispose, not Clear.

Upvotes: 4

Massimiliano
Massimiliano

Reputation: 17000

First remove a Tab from the collection, then Dispose(). Never Dispose() something that is still in use, as it will cause exceptions and strange behavior.

Also, ensure that no one else have references to the tabs, otherwise those references will become invalid on Dispose().

Upvotes: 2

Marty
Marty

Reputation: 7522

Calling Dispose() on each of the tab pages does not actually remove them from the TabPages collection, it simply disposes them. The call to Clear() is what removes them from the collection. If you don't call Clear() they will still be there, and bad things will likely happen because you will end up trying to use them after they have been disposed.

Upvotes: 2

Related Questions