Tuesday, February 12, 2013

SharePoint 2010 - Configurable Web Part Properties

In  the previous post, we created a Visual Webpart using visual studio. In this post we will discuss about web part properties and how to create configurable web part properties.

WebPart Properties
All Web Parts share a set of common properties that allow you to specify attributes for the appearance, layout, and other information. To view web part properties, click on the web part menu and select Edit web part".

On the right hand side you can see the web part properties window opens. Here you can make the basic changes like adjusting height, width, Title, etc.


Configurable WebPart Properties
Apart from the default properties, you may want to add you own custom properties which can be even used as parameters for the webpart. Configurable Web Parts are used to present a user-friendly interface for Web Parts configuration. The following attributes makes it possible to add custom properties.

The WebBrowsableAttribute class
The WebBrowsableAttribute class instructs the Web Parts infrastructure that the property has to be made available in the Web Part’s configuration panel. 

The PersonalizableAttribute class
The PersonalizableAttribute declares that the property can be personalized and defines the scope of the personalization. There 2 types of scopes:
1) Scope of type User, which means that the property can be personalized on a per-user basis.
2) Scope of type Shared, which means that the property personalization will be shared between all users.

Configurable WebPart Attributes
Following attributes enables the display of the custom properties in web part properties window.
1) [WebBrowsable(true)] - This will hide or show the property on the tool pane.
2) [Personalizable(PersonalizationScope.Shared)] - How the WebPart is configured, which can be per-user (PersonalizationScope.User), or for everyone (PersonalizationScope.Shared). 
3) [WebDescription("Description of List")] - Description for the property.
4) [WebDisplayName("My List Name")] - Label for the property.
5) [Category("Personalized Items")] - This will group your property according to category. If not declared, “Miscellaneous” will be used as the default.
6) [DefaultValue("Default")] - The default value for the property.

 Following are the steps for creating a Configurable Web Part Property :
1) Create two custom lists as follows:
i) "Products" with columns "Title", "Description" and "Price".
ii) "Customers" with columns "Title" and "Address".

2) Open Visual Studio and create a new Visual Web Part named MyVisualWP. In the "MyVisualWpUserControl.ascx" add a GridView control name "gvwProducts".

3) Open the solution in visual studio and modify the code in the Webpart file "MyVisualWP.cs" as follows. i) Add a configurable web part property named "ListName" using [WebBrowsable] attribute.
ii) Modify the CreateChildControls() to change the type of Control to Visual Web Part.
Following is source code for MyVisualWP.cs
Code Snippet
  1. namespace VisualWebpartDemo.MyVisualWP
  2. {
  3.     [ToolboxItemAttribute(false)]
  4.     public class MyVisualWP : WebPart
  5.     {
  6.  
  7.         [WebBrowsable(true),
  8.         Category("Personalize"),
  9.         WebDisplayName("List Name"),
  10.         WebDescription("Custom list name editable by user")]
  11.         [Personalizable(PersonalizationScope.Shared)]
  12.         public string ListName { get; set; }
  13.  
  14.         // Visual Studio might automatically update this path when you change the Visual Web Part project item.
  15.         private const string _ascxPath = @"~/_CONTROLTEMPLATES/VisualWebpartDemo/MyVisualWP/MyVisualWPUserControl.ascx";
  16.  
  17.         protected override void CreateChildControls()
  18.         {
  19.             MyVisualWPUserControl control = Page.LoadControl(_ascxPath) as MyVisualWPUserControl;
  20.             control.MyVisualWebpart = this;
  21.             Controls.Add(control);
  22.         }
  23.     }
  24. }

4) Now, go to the user control code behind file "MyVisualWPUserControl.ascx.cs" and modify code as highlighted below.
i) You will notice that we added a public property for getting the web part.
ii) Then we use the "ListName" property of the web part to specify the list name.
iii) We set the ViewFields property in the SPQuery object to display titles: Title", "Description", "Price"
and "Address".
Following is source code for MyVisualWPUserControl.ascx.cs
Code Snippet
  1. namespace VisualWebpartDemo.MyVisualWP
  2. {
  3.     public partial class MyVisualWPUserControl : UserControl
  4.     {
  5.         public MyVisualWP MyVisualWebpart { get; set; }
  6.         protected void Page_Load(object sender, EventArgs e)
  7.         {
  8.             if (MyVisualWebpart.ListName != null)
  9.             {
  10.                 SPSite oSite = SPContext.Current.Site;
  11.                 using (SPWeb oWeb = oSite.OpenWeb())
  12.                 {
  13.                     SPQuery oQuery = new SPQuery();
  14.                     oQuery.ViewFields = "<FieldRef Name='Title' /><FieldRef Name='Description' /><FieldRef Name='Price' /><FieldRef Name='Address' />";
  15.                     oQuery.ViewFieldsOnly = true;
  16.                     SPList oList = oWeb.Lists[MyVisualWebpart.ListName];
  17.                     SPListItemCollection oColl = oList.GetItems(oQuery);
  18.                     gvwProducts.DataSource = oColl.GetDataTable();
  19.                     gvwProducts.DataBind();
  20.                 }
  21.             }
  22.         }
  23.     }
  24. }

5) Deploy the solution and open the web part page in edit mode. 

6) Go to the web part properties and you can see the new custom property that we added.


7) Enter the list name "Products" and click "Apply" button, you will see the items in the Products List are populated in the GridView.

8) Now change the List Name to "Customers" and click "Apply" button. You will see the items in the Customers list will be populated in the GridView.

Note:- The above code defined property that requires the end user to configure the Web Part manually, typing the target list name autonomously and  made use of the standard behaviour of SharePoint and the out-of-the-box CustomPropertyToolPart.
But this is not a user-friendly and error-free approach. The right solution would probably be to provide a drop-down list with all the lists available in the current website, thereby avoiding typo errors and the consequent time consuming debugging tasks.
To customize the Web Parts’ configuration user interface you can create custom classes called "Editor Parts" which are controls hosted in a specific WebPartZone called EditorZone.

We will take a closure look on to Editor Parts in the next post

5 comments:

  1. Hi,The best web page design in this circumstance is generally to design a web page with multiple images and scripts. This type of Web Design Cochin is done with a more advanced web page design program and requires quite a bit of experience.Thanks.......

    ReplyDelete
  2. how can i make this code dynamic. i have given hard code value of list name but i want dynamic

    public partial class ContentSliderUserControl : UserControl
    {
    string Qry = " {0}";
    protected void Page_Load(object sender, EventArgs e)
    {
    if (!IsPostBack)
    {
    DisplayAnnouncements();
    }
    }


    private void DisplayAnnouncements()
    {
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
    using (SPSite site = new SPSite(SPContext.Current.Site.ID))
    {
    using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
    {
    SPList list = web.Lists["Announcements"];
    SPQuery query = new SPQuery();
    query.RowLimit = 10;
    query.Query = string.Format(Qry, DateTime.Now.ToString("yyyy-MM-dd"));
    rep1.DataSource = list.GetItems(query).GetDataTable();
    rep1.DataBind();
    }
    }
    }
    );
    }
    Improve question Permalink

    ReplyDelete
  3. how to impliment the same thing IN VISUAL STUDIO 2012

    ReplyDelete
  4. do u have a download links for your code?

    ReplyDelete
  5. No. I haven't attached the codes. The code mentioned in the blog is working and tested. Please let me know if you face difficulties.

    ReplyDelete

Note: Only a member of this blog may post a comment.