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"); } }
public class MyWebPartUserControl : UserControl { } public class MyWebPart : UserControlWebPart<MyWebPartUserControl> { protected override string UserControlPath { get { return "~/_controltemplates/my.user.controls/mywebpartusercontrol.ascx"; } } }
<%@ Assembly Name="My.Assembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1234abcd1234abcd" %> <%@ Control Language="C#" Inherits="My.Assembly.MyWebPartUserControl" %>
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.