Wednesday, January 11, 2012

Add custom web part properties to visual web part in SharePoint 2010

In this article we are going to discuss how can we add custom web part properties to a visual web part in SharePoint 2010.

 First of all to create a visual web part using Visual Studio 2010, you can see my other post here. By following the above article I have created a visual web part namely CustomVisualWebPartProperties. After creating that Visual Web part, I have deleted the default
VisualWebPart1 and I have added another visual web part namely CustomWebPartProperties.
Now look at the project structure and from there open the CustomWebPartProperties.cs file as
shown in the figure below.
Here we are going to add the properties. We can add properties like below into the class, remember the class is derived from the System.Web.UI.WebControls.WebParts.WebPart.

 [Personalizable(), WebBrowsable, Category("Our Custom Properties"), WebDisplayName("First Name")]
        public String FirstName { get; set; }

        [Personalizable(), WebBrowsable, Category("Our Custom Properties"), WebDisplayName("Last Name")]
        public String LastName { get; set; }

And you class code should look like below figure:

After modifying this Go to open the user control code file and write in the class as below:
  public CustomWebPartProperties WebPart { get; set; }
You can refere the attached project for the reference.
Now lets modify the code in the CreateChildControls() method in the same page like below:
  CustomWebPartPropertiesUserControl control = Page.LoadControl(_ascxPath) as
            if (control != null)
                control.WebPart = this;
In the next we will see how can we can we bind values from the properties. Just to let you know this properties will come while we edit the web part.
Now drag and drop two labels from the toolbox and put it on the user control. After that we will see how can we bind the values from the custom properties to the labels.
Open the code file of the user controm and in the page load write the below code.

lblFirstName.Text = this.WebPart.FirstName;
lblLastName.Text = this.WebPart.LastName;

Till here we have finished our development, Now we will do our deployment. Now do a F5.
Once you deploy the code, it will be available to the web part galery. So edit your web page on which you want to add the web part. Then add your web part.
Whenever you will first add the web part you will not be able to see anything, so go ahead and edit the web part properties like below figure:

Now look at the properties window like below figure

You will able to see the Our Custom Properties section in the web part properties dialog box. There you will able to see our custom properties First Name and Last Name. Enter some value and click on OK and the Save&Close the page, You will able to see the entered text box values in the labels in the web part.
Download Full Project (CustomVisualWebPartProperties)