16 out of 21 rated this helpful - Rate this topic

Create Visual Web Parts in SharePoint 2010

SharePoint 2010

SharePoint QuickStart Banner

Getting Started with Web Parts in SharePoint 2010:  Building Web Parts is one of the most common tasks that are performed by SharePoint developers. Learn to create and deploy Visual Web Parts that display hierarchical views of list items and SubWebs.

Applies to:  Microsoft SharePoint Foundation 2010 | Microsoft SharePoint Server 2010 | Microsoft Visual Studio 2010

Published:  March 2010

Provided by:  Frank Rice, Microsoft Corporation

In this article, you create and deploy a Web Part that displays hierarchical data in a tree structure. To complete this task, you must do the following:

Create a Visual Web Part Project

In this task, you create a Visual Web Part project in Microsoft Visual Studio 2010.

  1. Start Visual Studio 2010, click File, point to New, and then click Project.

  2. Navigate to the Visual C# node in the Installed Templates section, click SharePoint, and then click 2010.

  3. Select the Visual Web Part project template (see Figure 1), provide a name (such as, SampleWebPart), a location for your project, and then click OK.



    Figure 1. Select the Visual Web Part project type

    Select the Visual Web Part project type

  4. In the What local site do you want to use for debugging dropdown, select the site to use (such as http://localhost/sites/SampleWebSite). Also select the Deploy as a farm solution option and then click Finish.

    Note that after the project is created, Solution Explorer contains the default Visual Web Part named VisualWebPart1 (see Figure 2). Also see in Solution Explorer the presence of the Features and Package nodes. A feature organizes your application in a way that SharePoint Foundation understands. Features can be deployed to SharePoint Foundation at the site or Web level. The package contains features and other assets used when you deploy solutions to SharePoint Foundation.



    Figure 2. The SampleWebPart project in the Solution Explorer

    The SampleWebPart project in the Solution Explorer

Add a TreeView Control to the Web Part

In this task, you add a TreeView control to the design surface of the Web Part. The TreeView control displays a hierarchical view of lists and SubWebs.

  1. In Solution Explorer, expand the VisualWebPart1 node, right-click the VisualWebPart1UserControl.ascx file, and then click View Designer. This action opens a view to drag-and-drop controls from the toolbox onto the Web Part designer surface.

  2. From the Toolbox on the left side of the screen, click the Navigation section, and then drag a TreeView control onto the design surface. If you do not see the Toolbox on the left side of the screen, on the View menu, click Toolbox.

  3. Select the TreeView control and in the Properties panel in the lower-right corner of the Visual Studio screen, type the name siteStructure in the ID field.

Add Code to the Project

In this task, you add Microsoft Visual C# code to the project that iterates through all lists and SubWebs in the SharePoint site, and adds them to the TreeView control.

  1. In Solution Explorer, expand the VisualWebPart1UserControl.ascx node, right-click the VisualWebPart1UserControl.ascx.cs node, and then click View Code.

  2. Next, substitute the following C# code for the code in the code screen.

    using System;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Utilities;
    using System.Web;
    namespace BonnevilleTestBed.Bonneville
    {
      public partial class BonnevilleUserControl : UserControl
      {
        protected void Page_Load(object sender, EventArgs e)
        {
          SPWeb thisWeb = null;
          TreeNode node;
          thisWeb = SPContext.Current.Web;
          //Add the Web's title as the display text for the tree node, and add the URL as the NavigateUri.
          node = new TreeNode(thisWeb.Title, null, null, thisWeb.Url, "_self");
          //The Visual Web Part has a treeview control called siteStructure.
          siteStructure.Nodes.Add(node);
          //Get a reference to the current node, so child nodes can be added in the correct position.
          TreeNode parentNode = node;
          //Iterate through the Lists collection of the Web.
          foreach (SPList list in thisWeb.Lists)
          {
            if (!list.Hidden)
            {
              node = new TreeNode(list.Title, null, null, list.DefaultViewUrl, "_self");
              parentNode.ChildNodes.Add(node);
            }
          }
          foreach (SPWeb childWeb in thisWeb.Webs)
          {
            //Call our own helper function for adding each child Web to the tree.
            addWebs(childWeb, parentNode);
            childWeb.Dispose();
          }
          siteStructure.CollapseAll();
        }
        void addWebs(SPWeb web, TreeNode parentNode)
        {
          TreeNode node;
          node = new TreeNode(web.Title, null, null, web.Url, "_self");
          parentNode.ChildNodes.Add(node);
          parentNode = node;
          foreach (SPList list in web.Lists)
          {
            if (!list.Hidden)
            {
              node = new TreeNode(list.Title, null, null, list.DefaultViewUrl, "_self");
              parentNode.ChildNodes.Add(node);
            }
          }
          foreach (SPWeb childWeb in web.Webs)
          {
            //Call the addWebs() function from itself (i.e. recursively) 
            //to add all child Webs until there are no more to add.
            addWebs(childWeb, parentNode);
         childWeb.Dispose();
    
          }
        }
      }
    }
    
    
    

Build and Deploy the Web Part

In this task, you build and deploy the Web Part project.

Build and deploy the project by using one of the following options:

  • When debugging the SharePoint solution, use the F5 key to build and deploy your solution. By doing this, the debug experience includes steps such as help for creating a Web Part Page and resetting Internet Information Services (IIS).

  • Alternately, you can build and deploy your solution by clicking the Build menu, selecting Build Solution, verifying that the solution builds without any errors, and then selecting Deploy Solution.

Create a Web Parts Page

In this task, you create a Web Parts page to contain the Web Part, unless one has already been created for you.

  1. If you clicked F5 to debug your application, by default, the page where you create a Web part page is displayed. Otherwise, open the SharePoint site, click Site Actions, click View All Site Content, click Create, scroll and select the Web Part Page option.

  2. In the Web Part Page screen, provide the information requested about that particular Web Parts page. For example, provide a name (SampleWebPartPage) and layout template for the page.

  3. In the Document Library dropdown, select Site Pages, and then click Create. SharePoint creates and displays your Web Parts page.



Figure 3. A sample Web Part page

A sample Web Part page

Add the Web Part to the Web Parts Page

In this task, you add the Web Part to the Web Parts page and test the solution.

  1. On the Web Parts page, click into the Add a Web Part text in the zone where you want the Web Part displayed.

  2. In the Categories list, click Custom. In the Web Parts box, click VisualWebPart1.

  3. In the About the Web Part box at the top of the page, click Add. The Web Part is added to the zone that you selected as shown in Figure 4. Note that the lists and SubWebs are displayed in a hierarchical view.



Figure 4. The Web Part after being added to the zone in the Web Part page

The Web Part after being added to the zone

Next Steps

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
A case of mistaken project ID

The person writing the code and the person providing the instructions could not possibly be the same person, otherwise this screw-up would not have occurred.  Do the following:
 
1.    Project name:  "BonnevilleTestBed" NOT "SampleWebPart"
2.    Add another visual webpart to the project, call it: "Bonneville"
3.    Delete Webpart called "VisualWebPart1" or the old one whatever you named it.
4.    To "Bonneville" add the Treenode control
5.    To Bonneville set ID = "siteStructure"
6.    Go to code behind and clear everything and replace with the sample code provided
7.    Save everything
8.    On project explorer right click "build" or "Rebuild"
 
You should now have a clean project that compiles. 
 
I went on and tested it and it worked.  I did not do an in-depth analysis of the functionality because after all, this is a demo!  But it seem to work reasonably well.
If someone cannot seeing the Custom Folder for add web parts
If someone cannot seeing the Custom Folder for add web parts. Do the following:

1. Go To Site Action from you Share Point Site and Navigate to Site Settings
2. In site setting page select “Site Collection Features” under “Site Collection Administrator” Section.
3. There you will find the list of features that belongs to your site collection. Just search for your own web parts features. You will find it as “deactivate State” .
4. Click on the “Activate” Button. And return to see if you can find the Custom folder.

That's it!!!!!
siteStructure is not reading because namespace is wrong
After reading everyone's reply everyone confused me even more with their namespace they provided and then I realise namespace is declaring projectname.webpartname
the exact fix to this guide is


replace these two lines to this inside VisualWebPart1UserControl.ascx.cs

namespace SampleWebPart.VisualWebPart1

public partial class VisualWebPart1UserControl : UserControl


Still cannot get this to work...then try this!
If you still get the error "The name 'siteStructure' does not exist in the current context", in SPD look in the ascx.cs file and make sure that the "namespace" is the same as the "Inherits=" in the ascx file. 

As an example, my "namespace" was "FirstWebPart.VisualWebPart1", while my "Inherits=" was "SampleWebPart010212.VisualWebPart1". I changed the namespace to "SampleWebPart010212.VisualWebPart1" and the error went away.
Where do we put "thisWeb.Dispose()"
I am guessing before the last bracket but I am going to leave it off for now until I see an error.
siteStructure does not exist
If you get this error ( I am sure you will get it if you copy above code.) Then replace
namespace BonnevilleTestBed.Bonneville
{
  public partial class BonnevilleUserControl : UserControl

with

namespace FirsWebPart.VisualWebPart1
{
public partial class VisualWebPart1UserControl : UserControl

Also we need to dispose thisWeb oject. So Use

thisWeb.Dispose()
compile error
When I followed these instructions I got this compile error:

Error 1 The name 'siteStructure' does not exist in the current context C:\srclocal\VisualWebPartTry4\VisualWebPartTry4\VisualWebPart1\VisualWebPart1UserControl.ascx.cs 20 13 VisualWebPartTry4

Is the code supposed to work regardless of the name of the control?  I used the default as per the instructions.  

Do I need a Sharepoint site named BonnevilleTestBed?  The instructions do not mention the need for a specially named sharepoint site.
siteStructure does not exist
In case you get the above error while using the sample code please change the line to

public partial class VisualWebPart1UserControl : UserControl

This is what is the default incase you dont change the name of the class to Bonneville.
  • 9/29/2010
  • JJN
siteStructure does not exist
If you are still getting errors after following the instructions exactly, and also changing your code to show: $0 $0public partial class VisualWebPart1UserControl : UserControl$0 You also need to change the namespace. The namespace depends on your project's name and the name of your webpart. Change your code to the following: $0 $0namespace VisualWebPartProject5.VisualWebPart1$0 $0 $0VisualWebPartProject5 and VisualWebPart1 would change of course depending on whatever your project and webpart is called.$0 $0
Cant see "custom" category in categories...
Hello ppl..
I have created a sample visual webpart and deployed it. i have also created a webpart page on my team site. Now im trying to add the newly created webpart to the webpart page. But wheni say add webpart, i cannot see a category named "custom" in the categories section..obvioulsy i m not able to select my webpart..what am i missing here??
Deployment migration question
Is there an article on migrating development practice from MOSS to 2007 that provides all the details: $0$0 $0 $0WebPart vs User Control$0 $0GUIDS$0 $0Deployment Scope$0 $0 $0Partial Trust Security$0 $0Feature Manifest$0 $0$0 $0 $0$0 $0 $0$0 $0 $0$0 $0$0 $0$0 $0 $0 $0
siteStructure is a treeview control on the ascx
you need to add a treeview control on to the ascx and name it siteStructure. the code is referencing nothing because siteStruture doesn't exist yet
The name `siteStructure` does not exist in the Current Context
when i used this code i got following error?

The name `siteStructure` does not exist in the Current Context

any thoughts?