How to Add a User Control to a SharePoint Web Part

By default, when you create a visual web part in a SharePoint 2010 project, Visual Studio adds a user control for you and performs the necessary plumbing to ensure it gets deployed to the Control Templates directory in the 14 hive. This is all very fine until you want to model a dialog or secondary display mode as another user control; VS does not offer an easy or obvious way to add a user control inside a web part.

I figured out the procedure for this a few months ago at work, and it has been living on our internal wiki since then, so I thought I’d post it here. It assumes you want to create a user control called UserControl.ascx either directly inside a web part, or inside a folder inside the web part (given by OptionalFolderPath).

  1. Right click your project and add a new user control.
  2. Drag the user control from the default location (ControlTemplates\ProjectName) to your web part.
  3. Edit the web part .spdata file in the following way:
    • The target for the new user control is probably set to ProjectName\WebPart instead of CONTROLTEMPLATES\ProjectName\WebPart, like the original user control. Change it to match.
    • The source for the new user control is probably set to something like ‘..\WebPart\OptionalFolderPath\UserControl.ascx’. If you want, you can remove the first two redundant segments.
  4. Change the namespace of the user control from the godawful ControlTemplates one, to one of your choice (generally, the same as your web part). If you have Resharper, you can do this cleanly in one swipe. Otherwise, manually:
    • Rename the namespace in your user control code-behind
    • Update the Control directive near the top of the ascx accordingly.
  5. Reference your new user control. The path will be something like “~/_CONTROLTEMPLATES/ProjectName/WebPart/OptionalFolder/UserControl.ascx”:
    • If you’re referencing it from your web part .cs, call TemplateControl.LoadControl with the above path.
    • If you’re referencing it from your original user control, add a reference like: <%@ Register TagPrefix=”Controls” tagName=”UserControl” src=above path %>
This entry was posted in ASP .NET, SharePoint, Web and tagged , , , , , , . Bookmark the permalink.

2 Responses to How to Add a User Control to a SharePoint Web Part

Leave a Reply

Your email address will not be published. Required fields are marked *