Saturday, January 17, 2015

Adding Custom Properties to a Visual Web Part

When the Visual web part is generated in Visual Studio (Eg; VS 2013). It contains mainly 3 components. The web part file, user control a ASCX file and the code behind for the user control

The web part is generated with the following code in the CreateChildControls() method

private const string _ascxPath = @"~/_CONTROLTEMPLATES/15/....../MyWebPartUserControl.ascx";

protected override void CreateChildControls()
{
  Control control = Page.LoadControl(_ascxPath);
  Controls.Add(control);
}

Here, the .ascx could not access the custom web part properties.
When adding custom properties to the Visual web part,  few changes are required.

1) Create a property in the user control, of the web part class type.

public MyVisualWebPart ParentWebPart { get; set; }

2) Set the web part to the user controls parent property

Inside the web part file's CreateChildControls() method change the code to:

MyVisualWebPartUserControl control = (MyVisualWebPartUserControl)Page.LoadControl(_ascxPath);
//Set the web part to the users controls parent property                                                                             
control.ParentWebPart = this;
Controls.Add(control);    

Now the custom web part properties are accessible from the user control !                                                                                                              

3) Add the required custom properties into the web part file

        private string customPropertyOne;                           
        [Category("My WebParts Custom Settings"),           
        Personalizable(PersonalizationScope.Shared),          
        WebBrowsable(true),                                              
        WebDisplayName("Custom Property One"),            
        WebDescription("This is my first custom property")] 
        public string CustomPropertyOne                             
        {                                                                             
            get { return customPropertyOne; }                      
            set { customPropertyOne = value; }                    

        }                                                                            

4) Access the property in the ASCX file

Now you can access the custom property via:

ParentWebPart.CustomPropertyOne


No comments:

Post a Comment