Responsive Ads Here

Sunday, September 14, 2014

How to create a custom property and doing validation in SharePoint 2013 visual webpart

Let us see how to add new custom property to a Visual Web Part in SharePoint 2013 and how to validate the same.
Follow the below steps to create a custom property
1. Create a new SharePoint 2013 SharePoint Project
2. Add a Visual Web-part to that project
3. Create a new Text Property by adding the below code in the webpart.cs file of Visual Web-part. The below code creates new custom property  and validates the same.

 public string FeedURL;
[WebBrowsable(true),
WebDisplayName("Enter the valid URL:"),
WebDescription("Description"),
Personalizable(PersonalizationScope.Shared),
Category("Settings")]
        
public string rssFeedValidURL
{
    get
    {
       return FeedURL;
    }
    set
    {
       if (!string.IsNullOrEmpty(value))
       {
           Match match = Regex.Match(value, @"^((http|https):[/][/]|www.)([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?", RegexOptions.IgnoreCase);
           if (!match.Success)
           {
               throw new Microsoft.SharePoint.WebPartPages.WebPartPageUserException("The Rss Feed URL is not valid");
           }
        }
        FeedURL = value;
    }
}

The below code will illustrates how to access the custom property in visual web part. For this we need to to write the code in CreateChildControls() method which will be available in the webpart.cs file.


  
        /// 
        /// Create child Control for the web part
        /// 
        protected override void CreateChildControls()
        {
            //Control control = Page.LoadControl(_ascxPath);           
            //Controls.Add(control);          
            EventsUserControl control = (EventsUserControl)Page.LoadControl(_ascxPath);
            if (control != null)
            {
                control.rowLimitProperty = this;
            }
            Controls.Add(control);
        }

Below code will help us how to access the custom web part property in visual web part. we need to write the below code in the ascx file.

public partial class EventsUserControl : UserControl
    {
        #region [[Webpart Properties]]
        public Events Property { get; set; }

        #endregion

 protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                   string rssFeedurl = Property.rssFeedURL;
                }
            }
       }
}

For more information please go through the below links.

No comments:

Post a Comment