Create a Custom Web Part for SharePoint 2010

Author by Mark Rentmeester

Written by Jourdan Laik If you've ever tried searching the internet for some type of tutorial that walks you through the basics of creating a custom Web part in SharePoint 2010 you've probably noticed that most of them are fairly basic. More often than not you've mistakenly clicked off to a blog post that's not even related to SharePoint 2010 Web parts. If this has happened to you, you've also probably reached a point where you've got one eye on some obscure blog post about 2010, and the other on a forum post pertaining to 2007 all while trying to piece it all together only to really wonder: Am I doing this right? To add more fuel to the fire, have you ever tried to find out how to add custom properties to your Web part? Or perhaps how to add a dynamic dropdownlist control to the Web part properties? It's almost impossible to find any documentation that walks you through all the necessary steps to do this; to actually get you to the point where you've created a Web part that does more than just say "Hello World!" Well in this blog post, I'm going to show you the basics you'll need to create a SharePoint 2010 Web Part that is meaningful and that utilizes the following features:

  • User Controls
  • Code Behind
  • Custom Web Part Properties
  • Custom EditorPart(s) Properties
  • Accessing SharePoint Data within the Web Part


The Web Part I'll be demoing here doesn't do much of anything other than show you how to accomplish all the above features giving you the power to adapt the code so you can make a meaningful Web part for your own specific needs. Let's begin:


Creating the base Web Part

  1. Create a new SharePoint 2010 Empty SharePoint Project. Name it MyWebPartProject.
  2. Once it's been created, click on the project, choose Add > New Item.
  3. Choose the Visual Web Part template and name it MyWebPart.

We've now have a very simple Web part that we can build, deploy, and add to our pages in SharePoint. Of course, it wont show anything, but this it shows how simple it is to get a Web part skeleton setup to a compiled, deployable and usable state. Let me explain some of important files we'll focus on:

  • MyWebPartUserControl.ascx This UserControl files take care of all the visual front-end controls and functionality. It's associated MyWebPartUserControl.ascx.cs file takes care of the code-behind work.
  • MyWebPart.cs This file is the class that is used to handle all the behind-the-scenes functionality of your Web part. This where the Web Part is initialized, where it loads up, and references the UserControl.

All the other files that are in your project are necessary for the Web part to function, however you don't need to touch any of other files to get a custom WebPart (even at a very customized level) working. For now, just focus on the MyWebPart.cs, MyWebPartUserControl.ascx and MyWebPartUserControl.ascx.cs files.

Add some functionality

  1. Add an asp Label Control named lbl_MySelection to the MyWebPartUserControl.ascx file.
  2. Open the MyWebPartUserControl.ascx.cs file and override the OnPreRender method like such and add the following code to it:
    protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); lbl_MySelection.Text = "Please make a selection."; }
  3. Deploy the project to your SharePoint instance
  4. Edit a page and add your Web part to the page

We should now see some text that says, "Please make a selection." This demonstrates how and where to add custom code to interact with our UserControls' form controls (in this case our lbl_MySelection label).

Web Part Properties

When you edit a Web part, and the Web part editor pops up in your browser, each one of those options are called properties. We can add our own properties and in real development environments they're not a novelty but a necessity. Before we begin with the code, it's important to understand that there are two major categories to Web part properties:

  • Standard Toolbox Properties These are standard text fields, checkboxes, or dropdown lists that are able to receive data from the user and push those values to the Webpart. These do not display dynamic data. For instance: You couldn't use a standard dropdownlist property to display a list of items from a SharePoint list. This is because the there's no way to bind data to the dropdownlist, it uses a hard-coded enum in your Web part .CS file (more on this in the example code below).
  • Custom EditorPart Toolbox Properties These allow you to build up any type of asp control (or third party control) bind custom data to do (like list data from within SharePoint or an external database) and push these values to the Web part.

Creating Standard Toolbox Properties

  1. Open up your MyWebPart.cs file.
  2. Right before the private const string _ascxPath ... declaration, add the following code:
    [WebBrowsable(true), Category("Miscellaneous"), Personalizable(PersonalizationScope.Shared), WebDisplayName("Enter some text")] public string CustomTextProp { get; set; }
    The Category seen here can be any existing category within the Web part editor tool pane, or you can type your own custom category. The WebDisplayName option is what the label will say above the property. And of course, the final line is the actual property. If we deploy our project now, we will see our property show up in the Web part tool pane when editing the Web part, but it simply is a dummy property area. It doesn't do anything because we haven't tied the property to our MyWebPartUserControl. Let's do that now...
  3. Open the MyWebPartUserControl.ascx.cs file and right before the empty Page_Load() method, add the following property:
    public MyWebPart WebPart { get; set; }
    This will allow us to reference our other MyWebPart.cs class in this ascx code-beind class and ultimately expose the tool pane properties to us.
  4. Back in the MyWebPart.cs file, locate the CreateChildControls() method and replace it with the following:
    protected override void CreateChildControls() { MyWebPartUserControl control = Page.LoadControl(_ascxPath) as MyWebPartUserControl; if (control != null) control.WebPart = this; Controls.Add(control); } }
    This looks for our user control on the page and it's not null, we set the WebPart property (which we created in the previous step). Then we add the usercontrol to the controls collection.
  5. Switch back again to the MyWebPartUserControl.ascx.cs file. Locate the OnPreRender method and replace it with the following:
    protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); if (this.WebPart != null && this.WebPart.CustomTextProp!=null) { lbl_MySelection.Text = this.WebPart.CustomTextProp.ToString(); } }
    This is the final piece to the puzzle. We're setting the text field within our Web parts' user control to the tool pane's property text field.

Of course, you can do more than just text field type properties (the following code would be implemented in your MyWebPart.cs file:

  • Checkboxes
    [WebBrowsable(true), Category("Miscellaneous"), Personalizable(PersonalizationScope.Shared), WebDisplayName("Checkbox Option Text")] public bool CustomCheckboxProp { get; set; }
  • Dropdown Lists
    public enum ddlEnum { option1, option2, option3 } [WebBrowsable(true), Category("Miscellaneous"), Personalizable(PersonalizationScope.Shared), WebDisplayName("Dropdown List Display Text")] public ddlEnum ddlProp { get; set; }

As you can see so far, the standard tool pane properties are kind of limited; especially the dropdown list: we're tied to the enumeration. What if we wanted some SharePoint list data feeding that dropdownlist Control? To create fully customized tool pane properties, we need to create our own "EditorPart" and here's how to do it:

Creating custom EditorPart properties

We're going to create our own custom DropDownList control EditorPart that feeds in some values from a custom SharePoint list.

  1. In your root SharePoint site, create a new custom list. You can keep the new custom list really simple, or you can add your own custom fields; doesn't matter. If you'd like to use a already existing list, feel free to reference that list instead.
  2. Open your MyWebPart.cs file and after the private const string _ascxPath declaration add the following code:
    public string _OptionValue { get; set; }
  3. After the whole MyWebPart.cs class declaration, add the following class:
    public class MyEditorPart : EditorPart { private DropDownList ddl_Options; protected override void CreateChildControls() { base.CreateChildControls(); }   public override bool ApplyChanges() { EnsureChildControls(); MyWebPart webPart = WebPartToEdit as MyWebPart; if (webPart != null) webPart._OptionValue=ddl_Panels.SelectedValue.ToString(); return true; }public override void SyncChanges() { EnsureChildControls(); MyWebPart webPart = WebPartToEdit as MyWebPart; if (webPart != null) ddl_Options.SelectedValue = webPart._OptionValue .ToString(); } }
    This is the meat and potatoes, if you will, of what makes the custom EditorPart a reality. But there is some more tweaking to do in order for it all to work:
  4. Locate the CreateChildControls() method you created in the code in the previous step. Replace what's inside with the following:
    base.CreateChildControls(); ddl_Options = new DropDownList(); lbl_Options = new Label(); lbl_Options.Text = "Choose:
    	:"; using (SPSite site = new SPSite("http://" + Page.Request.Url.Host.ToString())) { using (SPWeb web = site.OpenWeb()) { SPList Forms = web.Lists["Side Panel Content"]; SPQuery qry = new SPQuery(); qry.Query = @"0"; SPListItemCollection SPLIC = Forms.GetItems(qry); if (SPLIC != null && SPLIC.Count > 0) { foreach (SPListItem SPLI in SPLIC) { string OptionTitle = ""; string OptionID = ""; if (SPLI["ID"] != null) PanelID = SPLI["ID"].ToString();            if (SPLI["Title"] != null) PanelTitle = SPLI["Title"].ToString();if (PanelTitle != "" && PanelID != "") ddl_Options.Items.Add(new ListItem(OptionTitle, OptionID)); } } } }Controls.Add(lbl_Panels); Controls.Add(ddl_Panels);
  5. Now, back in your MyWebPartUserControl.ascx.cs file, add the following line of code to your OnPreRender() method:
    lbl_MySelection.Text = WebPart._OptionValue;
    This will set the label in your Web part's User Control to the value of the DropDown list in your custom EditorPart tool pane property.


There you have it! A Web part that is fully functional and meaningful. The sky's the limit as to what you can do with this Web part as your base.

Download the Source

Download Custom Web Part Project This article was originally written by Jourdan Laik. It is moderated currently by Mark Rentmeester.

Mark Rentmeester

Director of Application Development Services