Wednesday 28 May 2014

Generate .ascx.g.cs file manually for visual webpart

Here are the steps:

Ensure the Project’s, not the Solution’s, “Site URL” is set to a valid SharePoint URL. (Impressive dependency, to regenerate your designer code locally, you need to have a valid working reachable SharePoint url)


Right click on .ascx file, select Properties, and update the property “Custom Tool” to “SharePointWebPartCodeGenerator”.


Right click on the .ascx file and click Run Custom Tool. At this point, if the “SampleWebPart1.ascx.g.cs” is regenerated, your frustration is acceptable.


Open the project.csproj file in Notepad++ or other editor, find the line SampleWebPart1.ascx.g.cs
You should see something like this:


<Content Include=”SampleWebPart\SampleWebPart.ascx”>
<Generator>SharePointWebPartCodeGenerator</Generator><LastGenOutput>SampleWebPart1.ascx.g.cs</LastGenOutput>
</Content>


Change the LastGenOutput value to SampleWebPart.ascx.g.cs


Go back to Visual Studio 2012 and it asks to Reload the project (or Discard). 


Reload the project.


Right click on .ascx file and Run Custom Tool again.


Voila, the 1 is gone and the file should be now called SampleWebPart.ascx.g.cs.

5 comments:

  1. Thant you very much. By now, this is the fastest and easiest way to solve this problem i have seen.

    ReplyDelete
  2. Thank you very much its worked for me..it helped a lot and saved my time

    ReplyDelete
  3. Fantastic! I had two generator files showing up for the same ASCX (designer.cs and g.cs) and so duplicate declaration of classes and variables. And it was all because I had previously followed another blogger's suggestion to add 'SharePointWebPartCodeGenerator' to resolve a different issue. Your blog reminded me of this change. How come code generation is so helpful and yet so damned frustrating??

    ReplyDelete
  4. I don't want to add a visual webpart in sharepoint. I just needed a GridView control so I added an ascx file. The ascx file generates .designer.cs file but does not generate InitializeControl() method and when I add SharePointWebPartCodeGenerator, it shows (designer.cs and g.cs) and duplicate declaration of classes and variables.

    ReplyDelete