Ensure You Remember EnsureChildControls()!

I was recently writing a pretty simple ASP .net webpart, and its respective webpart editor. I was however, getting a unexpected error when the webpart editor was opened by the user:

I was initially confused as I wasn't doing anything that would throw this type of exception. The code is pretty straight forward with just setting the value of the textbox, and I had initialized all of the controls in the CreateChildControls() method. The exception was occurring when the SyncChages() method was being called by the editorzone, and the webpart editor was being populated with the current settings.

Eventually I realized that I had not called EnsureChildControls() before SyncChanges() was being executed. This method is required to initialize your controls. It checks to see if the CreateChildControls method has yet been called, and if it has not, calls it.

An example of using EnsureChildControls in the SyncChanges method is as follows:

public override void SyncChanges()

{

EnsureChildControls();

CustomWebPart part = (CustomWebPart)WebPartToEdit; ;

if ((part != null))

{

//Sync!

}

}