The dreaded “The name ‘InitializeControl’ does not exist in this context” error when working with Visual Web Parts in Visual Studio 2012

This happens to me all the time when I’m working with Visual Web Parts in Visual Studio 2012, and I finally found a good solution here to fix it, which I summarize briefly below:

Problem

You’re building a Visual Web Part in Visual Studio 2012, and all of a sudden it fails to Build, with this error:

The name ‘InitializeControl’ does not exist in this context.

This usually happens when the “Site URL” property on your SharePoint project is pointing to an invalid or nonexistent site (don’t get me started about how stupid it is that VS can’t detect this and tell you…).  The reason the build fails is because VS needs to use the existing site to compile the “.ascx.g.cs” file that sits behind the “.ascx” visual web part.

Unfortunately, simply setting the Site URL property on the SharePoint project to a valid site doesn’t fix the issue.

Solution

I have tried several methods to fix this (this one worked, but it’s a pain).  I finally stumbled across this page, which explains (in a somewhat roundabout fashion, which is why I want to credit this author but summarize the steps more concisely) that the “.ascx.g.cs” file can be regenerated with the following steps:

  1. Right-click the visual web part (.ascx) that is causing the problem, and select Properties.
  2. Ensure that the “Custom Tool” property is set to “SharePointWebPartCodeGenerator”.
  3. Right-click the visual web part again and select “Run Custom Tool.”  This should re-generate the “.ascx.g.cs” file.

Done.  Good luck!

Advertisements

2 thoughts on “The dreaded “The name ‘InitializeControl’ does not exist in this context” error when working with Visual Web Parts in Visual Studio 2012”

  1. We have tried the same steps. but I have added a child custom control in html markup and due to .g.cs code not generated. please help how to fix it. thank

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s