Another Error Creating Control in the Design View with Object Reference Not Set in Visual Studio 2010

In a previous blog, Controls State: "Error Creating Control" in the Design View in Visual Studio 2010, I have discussed about an Error Creating Control issue related to accessing the Session state in the OnInit() method. Since then, I have discovered that the Error Creating Control will also show in the design view if we try to access any object not being instantiated at the design time inside the OnInit() method.

For example, in a web application project, in a code-behind file that is adding controls dynamically to a page, similar to what was discussed in the article How To Dynamically Add Controls to a Web Page , we have code that’s accessing an object that is null at the design time as shown below

OnInit

When you switch to the design view, you would see "Error Creating Control – xxx. Object reference not set to an instance of an object”, where xxx is a control on your page. Screen shot of the error is shown below

Error

A simple workaround for this issue would be to check if we are in the design mode at the top of the OnInit() method, below the base.OnInit() call.

FixOnInit

This is a bug in VS 2010 that we’re now calling the OnInit() method at the design time; we are considering a fix for this in a future release of Visual Studio.

Thank you,
-Anh
Visual Web Developer Team