Sunday, June 26, 2011

Custom properties in visual web parts

When you are developing visual web parts in SharePoint 2010 and you need to have custom properties in your web part you need to know few things in order to connect the webpart class file to user control code behind file in order to have access to the web part properties in the user control code behind file.  Following are the steps that you should go through:


1- put your custom properties in the web part class file.
    example:
        private static string _fbaurls = "";
        [System.Web.UI.WebControls.WebParts.WebBrowsable(true),
        System.Web.UI.WebControls.WebParts.Personalizable(PersonalizationScope.Shared),
        System.Web.UI.WebControls.WebParts.WebDisplayName("آدرس سیستمهای Forms Authentication "),
        System.Web.UI.WebControls.WebParts.WebDescription("آدرس سسیتمهای Forms Authentication را در این قسمت وارد کنید. برای جداسازی آنها از علامت ; استفاده کنید."),
        System.ComponentModel.Category("تنظیمات"),
        System.ComponentModel.DefaultValue("")]

        public string FBAUrls
        {
            get { return _fbaurls; }
            set { _fbaurls = value; }
        }

2- then you need to change the
CreateChildControls method as below to convert the page controls to the user control class:
        protected override void CreateChildControls()
        {
            SystemLinksWPUserControl control = (SystemLinksWPUserControl)Page.LoadControl(_ascxPath);
            Controls.Add(control);
        }

3- like the piece of code below define a consumer property in user control code behind file:
        private static string _fbaurls;
        public string FBAUrls
        {
            get { return _fbaurls; }
            set { _fbaurls = value; }
        }


4- in last step, map the properites in web part class file and user control code behinde file together in CreateChildControls method. It should be something like this:
        protected override void CreateChildControls()
        {
            SystemLinksWPUserControl control = (SystemLinksWPUserControl)Page.LoadControl(_ascxPath);
            control.FBAUrls = this.FBAUrls;
            controls.Add(control);
        }

1 comment: