How To Properly Group Partial Class Files in Visual Studio 2005
Partial classes have been a very useful addition to the .NET Framework. You’ve seen this before: Visual Studio 2005 places code-behind logic of every Web Form in a partial class. This allows you to split code into several files, each with a
public partial class Xxxx declaration to be eventually complied into one class.
Partial classes are extremely helpful when a class is party code–generated and partly written by hand, which is exactly what happens in VS 2K5: it is thanks to a code-gen’ed
.designer.cs class that you don’t have to list server controls in code-behind anymore. By hand, that is—it’s done for you automatically.
Adding new partial class files
What if PageA (shown in the screen shot) code-behind logic grows to a point where you want to split it into two physical files? For example, we want to move some code to PageA_p2.aspx.cs.
If you right-click on PageA.aspx, there’s no option to add a code file. You have to add a new file, PageA_p2.aspx.cs, to the project itself. Open the new code file and replace its declaration with
public partial class PageA.
Next, close the project and open the .csproj file (PartialClasses.csproj in this case) in a text editor. Find the following element:
<Compile Include="PageA_p2.aspx.cs"> <SubType>ASPXCodeBehind</SubType> </Compile>
and edit it as follows:
<Compile Include="PageA_p2.aspx.cs"> <SubType>ASPXCodeBehind</SubType> <DependentUpon>PageA.aspx</DependentUpon> </Compile>
Save the file, close it and open your project in VS 2K5 again. Your new file should be displayed under PageA.aspx, which is precisely what we were after.
I really don’t know if there’s an easier way. Visual Studio definitely should handle this scenario better.