Tuesday, January 30, 2018

User Control Viewer

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace UserControlViewer
{
    [ToolboxItemAttribute(false)]
    public class UserControlViewer : Microsoft.SharePoint.WebPartPages.WebPart
    {
        private Control _childControl = null;
        private string _userControlVirtualPath = "/_controltemplates/Sample.ascx";
        private string _errMessage = string.Empty;

         [Personalizable(), Category("User Control Path"), DefaultValue(""),
          WebBrowsable(true),WebDescription("User Control Virtual Path"),
          WebDisplayName("User Control Virtual Path")]
        public string UserControlVirtualPath
        {
            get { return _userControlVirtualPath; }
            set { _userControlVirtualPath = value; }
        }

        public UserControlViewer()
        {

        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            if (_userControlVirtualPath != string.Empty)
            {
                if (_childControl != null) return;
                _childControl = Page.LoadControl(_userControlVirtualPath);
                if (_childControl != null)
                    Controls.AddAt(0, _childControl);
            }
        }

        protected override void RenderWebPart(HtmlTextWriter output)
        {
            if (_errMessage != string.Empty) output.Write(_errMessage);
            if (_userControlVirtualPath != string.Empty ||
                _userControlVirtualPath.Equals("") == false)
                RenderChildren(output);
        }

        protected override void RenderChildren(HtmlTextWriter output)
        {
            try
            {
                this.EnsureChildControls();
                if (this._childControl != null)
                    this._childControl.RenderControl(output);
            }
            catch (Exception ex)
            {
                _errMessage = string.Format(
                  "Exception Message (RenderWebPart) = {0}
", ex.Message);
            }
        }

        public override void Dispose()
        {

        }
         
    }
}

No comments:

Post a Comment