Its common practice to use a user control in a web part via LoadControl(...). By doing this you get the ASP.NET designer experience when working with .ascx files.
After seeing some implementations of encapsulating a user control in a web part, I created a version that uses a generic base class that has the benefits of giving strongly typed access to the user control, the class is as follows.
public abstract class UserControlWebPart<T> : WebPart where T : UserControl
{
/// <summary>
/// The control in the ASCX file
/// </summary>
protected T UserControl
{
get;
set;
}
/// <summary>
/// Path to the ASCX file
/// </summary>
protected abstract string UserControlPath
{
get;
}
protected override void CreateChildControls()
{
base.CreateChildControls();
if (!string.IsNullOrEmpty(this.UserControlPath))
{
this.UserControl = (T)this.Page.LoadControl(this.UserControlPath);
this.UserControl.ID = "uc";
this.Controls.Add(this.UserControl);
}
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
EnsureChildControls();
}
protected override void Render(HtmlTextWriter writer)
{
if (this.UserControl != null)
{
this.UserControl.RenderControl(writer);
}
else
{
writer.Write("UserControlPath is an invalid path, it must point to a valid .ascx file");
}
}To use this class you can just subclass it and implement the abstract property to define the path to the ascx file as follows.
public class MyWebPartUserControl : UserControl
{
}
public class MyWebPart : UserControlWebPart<MyWebPartUserControl>
{
protected override string UserControlPath
{
get { return "~/_controltemplates/my.user.controls/mywebpartusercontrol.ascx"; }
}
}The MyWebPartUserControl is the code-behind for the ascx file specified for the abstract UserControlPath property, this file requires a fully qualified assembly path to work correctly within sharepoint as follows.
<%@ Assembly Name="My.Assembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1234abcd1234abcd" %>
<%@ Control Language="C#" Inherits="My.Assembly.MyWebPartUserControl" %>