We are experts on the entire Microsoft enterprise product stack. These are Microsoft technologies we regularly deploy. We provide real business value through strategic guidance, technical expertise, and knowledge transfer.

As an IT systems integrator, our expertise is putting all the pieces together to get the job done, so we never have to take “no” for an answer. We help organizations improve business productivity in any department.

We provide solutions customized to the needs of your industry. Whatever your industry or product, we can provide project, service, process, and content management solutions—to increase productivity and IT value.

+1 (866) 930-8356
Concurreny
Real Microsoft expertise. Real business value.

Create a Custom Web Part for SharePoint 2010

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 = “<strong>Choose:</strong><br />:”;
    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 = @”<Query><Where><Gt><FieldRef Name=’ID’ /><Value Type=’Counter’>0</Value></Gt></Where></Query>”;
    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.

Conclusion

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 heads Concurrency’s Business Process Management practice. He has been a lead in software development and consulting teams for the past 15 years with a focus on applications with integration to line of business systems. His core areas of interest are BPM planning and systems architecture with ASP.NET, WCF, and SQL Server.

Find Mark on: Linkedin Twitter

 
  • http://YourWebsite Kevbo

    First great blog post, detailed and organized, its a great start for getting into web part development for 2010. Also this is a nice looking blog in general with a clean and easy to read blog homepage. I’ll be adding this to my favorites and visiting more often :) Thanks

  • http://www.linkedin.com/in/jourdanlaik Jourdan Laik

    Thanks Kevbo. I hope it can provide a good basis for developers looking to create their own Web parts.

  • http://YourWebsite Sol

    Nicely done, helped me a lot especially the “control.WebPart = this;”. I was in such a rush and overlooked this in my development.

    Thanks

  • http://YourWebsite T

    How in the world do you add a webpart in sp2010? i uninstalled it from GAC and also took it off from the webpart gallery..but now i need it back and i have the dll, installed it in c:windowsassembly, put it in the bin folder in wwwroot…but now, i can’t populate the webpart gallery with it.

    seriously need help…

  • http://www.linkedin.com/in/jourdanlaik Jourdan Laik

    T, how was the Web part initially installed? Sometimes a WebPart can be deployed right from within Visual Studio. If you’re not the developer, then sometimes it can be deployed within a wsp (Sharepoint Solution) file.

  • Scott

    Excellent work!
    This is exactly what I needed. A tutorial that actually made sense and followed through with exactly how to create different types of custom properties.
    Thanks a ton!

  • http://www.concurrency.com Steven Fischer

    Excellent post, Jourdan. It’s nice to see some straight-forward guidance on this topic.

  • http://YourWebsite Rajesh

    Good work, straight forward.

  • http://YourWebsite Don Lundman

    Didn’t your WebPart forget to implement IWebEditable?

    EditorPartCollection IWebEditable.CreateEditorParts()
    {
    List editors = new List();
    editors.Add(new MyEditorPart());
    return new EditorPartCollection(editors);
    }

    object IWebEditable.WebBrowsableObject
    {
    get { return this; }
    }

    The MyEditorPart class has many errors (typos). At some point you switched “Panel” to “Option” in variable names but not all references got the names changed.

    MyEditorPart also needs to assign an ID. You could do it in the default constructor:

    public MyEditorPart()
    {
    this.ID = “MyEditorPart”;
    }

  • http://YourWebsite Don Lundman

    Sorry to nit pick but compilers are very demanding. In the MyEditorPart class, just below the declaration for ddl_Options, add:

    private Label lbl_Options;

  • http://YourWebsite josetellan

    Great post. This is what I was looking for. but…if you dont mind….I want to ask you something similar. I want to create web content editor web part properties to get an image source (from SP list) and one url typed by user (about SP or internet) and i was wondering how to get those textbox values and insert them into the HTML code i write in web content editor WP. Is that possible?? maybe there is another easier way…trying other kind of wp

  • http://www.linkedin.com/in/jourdanlaik Jourdan Laik

    @Don:
    Thanks for reading my post so thoroughly and reporting back on what you found, I appreciate that. Sometimes in the transfer of actual code to the blog world things get a little mistranslated. You’re correct though, there are some discrepancies with the variable names I used, I will make those updates ASAP. However, I am not sure that the code you provided as necessary is all that necessary. Within the context of what we’re trying to do here, all code presented will get a Web part up and running and editable within SharePoint. Perhaps I am misunderstanding the actual purpose of your code or why you think I require it in my example.

    @josetellan:
    I’m glad this was able to help you! As far as adding custom properties to the Web Content Editor Web part, you can’t; unless there’s a way to extend the properties in the API that I am unaware of. You’re best bet is to create a new custom Web part and either inherit the Web Content Editor web part or write your own from scratch.

  • http://www.linkedin.com/in/jourdanlaik Jourdan Laik

    @josetellan:
    One of my SharePoint colleagues here at Concurrency (Mark Rentmeester) pointed me to a blog post by James McCormack that doesn’t extended the Content Editor Web part (because you can’t), but he used reflector and made his own:
    http://zootfroot.blogspot.com/2010/09/develop-custom-editable-visual-web-part.html

  • http://YourWebsite Pheobe

    Thanks Jourdan!
    It really helps.

  • Pheobe

    But, the part of Creating custom EditorPart properties seems to have lost some code..
    Can you update it?
    Thanks again.

  • abc

    Can any one help with this step -
    Add an asp Label Control named lbl_MySelection to the MyWebPartUserControl.ascx file.

    how do you add a asp label ?

  • http://YourWebsite Guilherme Santos

    Great job! Good guidance. It’s helped me a lot.

  • http://YourWebsite Gary

    Thanks Jourdan, but after mulling through all of the errors, the dropdown still does not display in the web part. Maybe it’s because I’m using SP 2010, and VS 2010, but it’s a no go.

  • http://www.egyptenportalen.se/ Marcus Andersson

    Excellent tutorial! Just what I needed to get up and running with basic web parts in SharePoint 2010.

  • http://YourWebsite Alt

    If I have more than one copy of the Web Part in my site, when I change the custom properties in one, it does it for all of them! How do I target just the one I changed????

  • Arun

    It will be better if you provide the source code with this example. As per your tutorial I succeed to customize the standard tool pane. But in the case of custom editor tool pane example I didn’t. Actually I wasn’t able to see my custom tool pane instead of my default tool pane.

  • http://www.linkedin.com/in/jourdanlaik Jourdan Laik

    The source can now be downloaded. Check the link at the end of the article.

  • http://YourWebsite Sam D

    Hi!
    This was an excellent article! I am doing something similar and struggling with how to get it working. The article I’m following is http://debapk.blogspot.com/2010/02/few-days-back-i-got-requirement-to.html and it has code for a custom control. I think (?) that this is a little different from your example since there is no web part and there is code that needs to be referenced in the master page to load the control. But I am not sure what that code needs to be (a great example of an incomplete tutorial lol!). Thank you very much.

  • http://YourWebsite HC Chan

    I couldn’t find the place to change the Site URL property of the project.
    IIS was looking at http://intranet.wingtip.com.

    Even though I hardcode the spsite url to my local server.

    Great article!
    Thanks
    HC

  • http://abemiester.com Abe Miessler

    I downloaded the source but it only appears to work with the static drop down list of items. I followed your instructions but was never able to get the drop down working with an internal list. Is this possible to do by following the instructions you have provided? If so, would it be possible to get you to post up the working code for that?

  • http://YourWebsite Spoorthy

    Its really a very good article for new bies of SharePoint.

    I have a similar thing required where i need to add datepicker as a web aprt property. I have used ‘DateTime’ but it is adding only textbox but not the datepicker. Then I tried with ‘DateTimeControl’, but this time i was not able to add my webpart to the page. What control i need to use in order to get datepicker control in SharePoint 2010.

  • http://YourWebsite Eran Rosenberg

    Great Article.

    I was wondering if i can store some fields in the elements.xml of the webPart
    and then read it from that file(i get null in the return value).
    elements.xml ex:

    code ex:
    control.Path = SPContext.Current.Web.Properties["XmlPath"];

  • http://YourWebsite Eran Rosenberg

    the elements.xml example is

    PropertyBag ParentType=”Web”
    Property Name=”XmlPath” Type=”string” Value=”Value” /Property
    /PropertyBag

  • http://ca.gov Nick Geier

    It seems to me you left out the most basic of steps required to do any of the above. First you have to have a 64 bit machine with Sharepoint Server running on it, because when I try step “1.” it says I don’t have Sharepoint Server running on this machine and won’t even open a template for a Sharepoint project. Is there any other way to create custom web parts?

  • http://YourWebsite Naren

    Whether the project shuld be given as either Sandboxed Solution or Farm Solution. You have not mention it anywhere. Because, i had a doubt of whther visual web part can be deployed it as sandboxed solution? If possibl, how? Please, help me. Thanx in advance.

  • http://www.actionforchildren.org.uk Paul Perry

    @Nick Geier:

    If you have a decent laptop with 4GB or more, you can run VS 2010 and SP2010 Foundation easily, just remember: A 64bit OS is needed beforehand.

    P

  • Russ

    The code in this post still has the syntax errors from the variable name changing 1/2 way thru. I downloaded the source project, but the project threw an error trying to open. Once I fixed the syntax errors, the custom web part properties were not showing up.

    I ended up finding a working solution here:
    http://www.nerdyhearn.com/blog/128

  • Russ

    Oh, and since the comment dates seem to be locked at 09.09.10 in this BLOG, I’ll add the actual date manually:
    08.01.11

  • Pingback: SharePoint 2010: Visual Webpart tutorial « Thornton Technical

  • http://YourWebsite Abu Hamzah

    Hi Jourdan Laik:

    I need your help, I am new to SP and i am struggling to find out what is the best way to achieve, I am working on SharePoint 2010 and Visual Studio 2010 and i will be creating the web-parts to meet the following business requirement:

    -create a web-part to display the html page and provide the text-box (as a property to enter the URL)

    the html content item is a part of an html page content could be return as a script (document.write() statements or an XHTML snippet)

  • http://YourWebsite Alex C

    Very nice article. I’ve been looking for this for some time and couldn’t find anything. Thanks for posting this.

  • waqas

    please i need help i have created calender in sharepoint 2010 now i want to add webpart “drop down list” in dropdown list i want to show calender next four and previous events from today date plzz someone help me…..

  • http://YourWebsite Threela

    Thank you, great post! Do you by any chance know how I can add a label tot the to the web part properties. I need to put a link on the properties pane which takes the users to a page where they can find the configuration options for the web part.

  • http://YourWebsite James

    Does anone know how to display an HTML page in a sharepoint web part. I want to display information from a sharepoint list on a map. I can read the list and I can bring the map up in an HTML page I just dont know how to combine them.

  • http://YourWebsite Asma

    Thank You so much for this post!! Assisted quite a bit in getting familiar with custom Visual WebParts.

  • http://YourWebsite Asma

    Hey actually.. it didn’t work for me when I had:
    [WebBrowsable(true),
    Category("Miscellaneous"),
    Personalizable(PersonalizationScope.Shared),
    WebDisplayName("Enter some text")]

    before the _ascxPath.. well it worked but I got a bunch of JavaScript errors and when I put that little piece of code underneath the the _ascxPath it worked… does anyone know why that is?

    I really want to know why in your blog you said to place the piece of code I pasted before the _ascxPath

    Let me know when you can & if you could please shoot me an email at the same time too.

    Thanks a bunch!!

  • Pingback: Multiple instances of webpart with custom EditorPart properties « Techyard’s Blog

  • http://YourWebsite Harish

    Hi Jourdan,

    This Blog is Really for new Developers…..
    Can we implement the same process in sandbox solution (using SPpowertool) for Visual web part…

    Please do the needfull.

    Thanks in Advance.

  • http://www.deepsharepoint.blogspot.com Deepak Semwal

    Very nice post, gonna add this in my blog.

  • http://www.deepaksharepointsp.blogspot.com Deepak Semwal

    Really nice description.

    thnks,
    Jourdan Laik

  • http://YourWebsite kiriti

    I have a requirement of adding repeater in the custom editor part. How can this be acheived

  • M M

    I am trying to customize a webpart and I am not a developer. I have never developed a web part outside of using what I can within the browser. I work with a vendor to do my work and due to my organizations funds, my contract is on hold and my site still needs to be developed. With that said, how do I apply the above noted knowledge? Am I going into SP Designer and in the code view just pasting it? What do I do? Please help. Thanks!

  • http://www.bellamysit.com/SitePages/Home.aspx parker harrison

    this is a super great article, i will be linking this page to clients a work with at http://www.bellamysit.com because sometimes i swear they just don’t get it. this article is very clear. thank you, you are godsend

  • http://www.bellamysit.com/SitePages/Home.aspx parker

    good site, good article. I’ll for sure be reading up on updates made by you. bring to light some good topics

  • http://www.bellamysit.com/SitePages/Home.aspx Chloe Scott

    Great tutorial. Very detailed.

  • Satish Singh

    Yes, it is good article, i have created it in my application.
    I want to add dropdown in webpart property, on that changed , i want display that related in another dropdown within webpart property .

    Please guide me .

  • http://profadmins.com karim

    check this free webpart and how to deploy it step by step
    http://profadmins.com/2012/06/07/fusion-charts-free-for-sharepoint/

  • Pingback: How to deploy a SharePoint WSP | Qian's Blog

  • Suresh Balaji

    The line
    lbl_Options = new Label();
    shows an error that lbl_Options doesnt exist..Can u help me out ???

    • b1c10

      of course, the error is not type defined:

      Label lbl_Options = new Label();
      simples :)

Categories