Web Developer, Software Engineer and Mixed Language Artist
RSS icon Email icon Home icon
  • Visual Studio – Lost nesting of codebehind

    Posted on April 30th, 2010 Jamie No comments

    We’ve all had times when we’ve created an ASP.NET webpage and then a new page is required with almost identical functionality.

    I had that task today and so making things simple I copied the current files, pasted them and made the necessary changes to hook the designer and code-behind files to the aspx page.

    This works perfectly. The code builds, the page runs, everything happens as I expected it to.

    Then I noticed a little quirk in Visual Studio 2008. One of the great features of Visual Studio is the way in which it visually nests code-behind files in the Solution Explorer under your aspx file.

    After making a copy of my origional page I noticed that my code-behind was left astray. I checked all the references to make sure everything was hooked up correctly but still, my code-behind wasn’t nesting nicely under my aspx page as usual.

    Now I’m sure many people have come across this problem before however this was a first for me.

    It turns out that the references are stores in the csproj file. There is a reference to the code-behind file and a list of dependancies. By default, when doing a copy/paste of files outside of Visual Studio, this reference is not updated and the code-behind file doesn’t attach itself to the aspx file in the Solution Explorer.

    The solution is to simply add a reference to the dependant aspx fie in the csproj file like so:

    <Compile Include="myShinyNewFile.aspx.cs">
    <DependentUpon>myShinyNewFile.aspx</DependentUpon>
    <SubType>ASPXCodeBehind</SubType>
    </Compile>

    Once you’ve added the second line into the csproj file, restarting visual studio brings back the much loved nesting.