Friday, August 02, 2002

Windows Forms Bug

Here's an interesting bug that causes a Windows Form to enter a state where it cannot be closed. I'm using the initial version of the .NET framework with SP1 installed.

Steps to reproduce: Create a new form, A. Put a user control B onto it. Put another user control, C, onto the control B. Finally, put a button onto C. At this point you should have something like this:

Form A, user controls B and C, and a button.

Write an event handle for the button click that causes the user control C to be removed from its parent, B.

Now, run the app and click on the button. You should end up with a form that looks like the one below. Now try to close the form by clicking on the close button - doesn't work, right?

Form A cannot be closed now.

Cause: The form is refusing to close because its Close method is trying to validate the control first, and validation fails because its unvalidatedControl private member still points to the button which has been removed from the hierarchy.

Workaround: After removing the user control C, call a.OnControlRemoved (c) in order to clear the unvalidatedControl variable.

Code: If you want to try this yourself a demo project can be found here.

   12:32 PM

Content of this site is © Dejan Jelovic. All rights reserved.