Creating SharePoint 2010 Visual Web Parts in Visual Studio 2010

SharePoint Visual How To

Summary:  Learn how to create a Visual Web Part for SharePoint 2010 by using Visual Studio 2010.

Applies to: Office 2010 | SharePoint Foundation 2010 | SharePoint Server 2010 | Visual Studio | Visual Studio 2008 | Visual Studio 2010

Provided by:  Ben Hedges, Point8020

Overview

Visual Web Parts enable developers to build Microsoft SharePoint 2010 Web Parts by using a design surface in Microsoft Visual Studio 2010. This functionality enables developers to drag user controls from the Toolbox to build the Visual Web Part's user interface.

Code It

This SharePoint Visual How To walks through the following process of creating and deploying a SharePoint Visual Web Part that uses LINQ to SharePoint. You will do the following:

  1. Generate an entities file in the SPMetal command-line tool.

  2. Create a Visual Web Part project in Visual Studio 2010.

  3. Add the entities file to the Visual Studio project.

  4. Retrieve data and display it in a Treeview control.

You will create a Visual Web Part that queries the contents of two joined SharePoint lists by using LINQ to SharePoint.

Prerequisites

The Visual Web Part requires two SharePoint lists, Candidates and Interviews, which are joined by using a lookup field.

To create the two SharePoint lists

  1. Create a list named Candidates that has the following columns:

    • Title (Default column)

    • Name (Single line of text)

    • HomeCity (Single line of text)

  2. Create a list named Interviews that has the following columns:

    • Title (Default column).

    • Date (Date and Time).

    • Candidate (Lookup to Candidate list by using the Name column).

    • Outcome (Choice; Pending, Rejected, Offered).

    • Interviewer (Person or Group).

To create sample data to use

  1. Create sample candidates that you will assign to interview events.

  2. Create sample interviews that include those candidates.

Creating the Visual Web Part

The following steps describe how to create the Visual Web Part.

To create an entities file for LINQ to SharePoint

  1. Open a Command Prompt window, and then navigate to the path C:\program files\common Files\Microsoft Shared\Web Server Extensions\14\BIN. This location may be different on your installation.

  2. At the command prompt, type the following (change the URL to match your deployment).

    Spmetal /web:http://intranet.contoso.com /code:c:\temp\entities.vb
    Spmetal /web:http://intranet.contoso.com /code:c:\temp\entities.cs
  3. Close the Command Prompt window.

To create a SharePoint 2010 Visual Web Part by using Visual Studio 2010

  1. Start Visual Studio 2010.

  2. On the File menu, click New, and then click Project.

  3. In the Installed Templates section, expand either Visual Basic or C#, expand SharePoint, and then click 2010.

  4. In the template pane, click Visual Web Part.

  5. In the Name text box, type InterviewSummary.

  6. Leave other fields with their default values, and then click OK.

  7. In the What local site do you want to use for debugging? combo box, select your site.

    Note

    You can deploy a Visual Web Part only as a Farm Solution.

  8. Click Finish.

To include the LINQ to SharePoint references

  1. In Solution Explorer, right-click InterviewSummary, and then click Add Reference.

  2. In the Add Reference dialog box, click the Browse tab, and then browse to the path C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI.

  3. In the selection box, click Microsoft.SharePoint.Linq.dll, and then click OK.

To add the entities file that was created by SPMetal

  1. In Solution Explorer, right-click InterviewSummary, click Add, and then click Existing Item.

  2. Browse to the path C:\temp, pick the entities file that you created in the earlier procedure, and then click Add.

To add a Treeview control to the User control

  1. Ensure that the file VisualWebPart1UserControl.ascx is open.

  2. At the bottom of the main window, click the Design view.

  3. In the Toolbox, from the Navigation section, drag a Treeview control to the design surface.

  4. Right-click the design surface, and then click View Code.

  5. Replace the code with the following.

    Imports System
    Imports System.Web.UI
    Imports System.Web.UI.WebControls
    Imports System.Web.UI.WebControls.WebParts
    Imports Microsoft.SharePoint
    Imports Microsoft.SharePoint.Linq
    Imports System.Linq
    
    Partial Public Class VisualWebPart1UserControl
        Inherits UserControl
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
            Dim thisWeb As SPWeb = SPContext.Current.Web
            Using ctx As EntitiesDataContext = _
                New EntitiesDataContext("http://intranet.contos.com")
                Try
                    Dim query = From interviews In ctx.Interviews _
                    Select interviews.Title, interviews.Candidate.Name,
                   interviews.Candidate.HomeCity, _
                    interviews.InterviewerImnName
                    For Each item In query
                        Dim interviewTreeNode As TreeNode = _
                        New TreeNode("Interview Details:" + item.Title, Nothing, Nothing, _
                                     thisWeb.Lists("Interviews").DefaultViewUrl, "_self")
                        Dim applicantTreeNode As TreeNode = _
                        New TreeNode("Applicant:" + item.Name, Nothing, Nothing, _
                                     thisWeb.Lists("Candidates").DefaultViewUrl, "_self")
                        Dim homecityTreeNode As TreeNode = _
                        New TreeNode("Home City:" + item.HomeCity, Nothing, Nothing, _
                                     thisWeb.Lists("Candidates").DefaultViewUrl, "_self")
                        Dim interviewerTreeNode As TreeNode = _
                        New TreeNode("Interviewer:" + item.InterviewerImnName, Nothing, Nothing, _
                                     thisWeb.Lists("Interviews").DefaultViewUrl, "_self")
                        interviewTreeNode.ChildNodes.Add(applicantTreeNode)
                        interviewTreeNode.ChildNodes.Add(homecityTreeNode)
                        interviewTreeNode.ChildNodes.Add(interviewerTreeNode)
                        TreeView1.Nodes.Add(interviewTreeNode)
                    Next
                Catch ex As Exception
                    TreeView1.Nodes.Add(New TreeNode("err" + ex.Message))
                End Try
            End Using
        End Sub
    
    End Class
    using System;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using Microsoft.SharePoint.Linq;
    using System.Linq;
    using Microsoft.SharePoint;
    namespace InterviewSummary.VisualWebPart1
    {
        public partial class VisualWebPart1UserControl : UserControl
        {
            protected void Page_Load(object sender, EventArgs e)
            {
    
                SPWeb thisWeb = SPContext.Current.Web;
    
                using (EntitiesDataContext ctx = 
                    new EntitiesDataContext("http://intranet.contos.com"))
                {
                    try
                    {
                        var query = from interviews in ctx.Interviews
                         select new { interviews.Title, interviews.Candidate.Name, 
                             interviews.Candidate.HomeCity, interviews.InterviewerImnName };
    
                        foreach (var item in query)
                        {
                            TreeNode interviewTreeNode = 
                                new TreeNode("Interview Details:" + item.Title, null, null, 
                                    thisWeb.Lists["Interviews"].DefaultViewUrl, "_self");
                            TreeNode applicantTreeNode = 
                                new TreeNode("Applicant:" + item.Name, null, null, 
                                    thisWeb.Lists["Candidates"].DefaultViewUrl, "_self");
                            TreeNode homecityTreeNode =
                                new TreeNode("Home City:" + item.HomeCity, null, null, 
                                    thisWeb.Lists["Candidates"].DefaultViewUrl, "_self");
                            TreeNode interviewerTreeNode = 
                                new TreeNode("SplInterviewer:" + item.InterviewerImnName, null, null, 
                                    thisWeb.Lists["Interviews"].DefaultViewUrl, "_self");
    
                            interviewTreeNode.ChildNodes.Add(applicantTreeNode);
                            interviewTreeNode.ChildNodes.Add(homecityTreeNode);
                            interviewTreeNode.ChildNodes.Add(interviewerTreeNode);
                            TreeView1.Nodes.Add(interviewTreeNode);
    
                        }
                    }
                    catch (Exception ex)
                    {
                        TreeView1.Nodes.Add(new TreeNode("Err" + ex.Message));
                    }
                }
    
            }
        }
    }

To modify the category for the Visual Web Part

  1. In Solution Explorer, expand VisualWebPart1, and then open Elements.xml.

  2. In the Property element, modify the Value attribute from Custom to Recruitment, as shown in the following markup.

    <Property Name="Group" Value="Recruitment" />

To deploy the project

  1. In Solution Explorer, right-click the project, and then click Deploy.

  2. In SharePoint, on a standard Web Parts page, click Edit Page above the Server ribbon.

  3. On the ribbon, in the Editing Tools group, click the Insert tab.

  4. On the ribbon, click Web Part.

  5. In the Categories section, click the Recruitment category.

  6. In the Web Parts section, click VisualWebPart1.

  7. In the About the web part section, click Add.

  8. On the ribbon, click Save.

The Visual Web Part displays the interviews and interview details in a Treeview control by using LINQ to SharePoint to retrieve data from the joined lists.

Read It

This Visual How To shows the following:

  • The solution uses LINQ to SharePoint to retrieve the contents of two lists, an Interview list and a Candidate list.

  • The lists are linked in SharePoint through a lookup field, with the Interviews list linking back to the Candidates list. This provides the information needed to join the lists in the LINQ query.

  • To use LINQ, the SPMetal command-line tool is used to generate an entity class, which provides an object-oriented interface to the lists and libraries in the SharePoint deployment. The entities file that is generated is added to the Visual Web Part project, and a reference is added to the Microsoft.SharePoint.Linq assembly through the using or imports statements to System.Linq and Microsoft.SharePoint.Linq.

  • The code creates a DataContext, and then uses a LINQ to SharePoint query to retrieve data from the lists.

  • An implicitly typed object is used in the foreach statement to build the Treeview control.

See It

Watch the video

> [!VIDEO https://www.microsoft.com/en-us/videoplayer/embed/8590abed-8726-4671-8061-fdd74cb43b39]

Length: 00:05:32

Click to grab code

Grab the Code

Explore It

About the Author

Community Contributor  Ben Hedges is Senior Vice President, Research and Development at Point8020. Ben is particularly interested in modeling Talent Management, Compliance, and Learning and Development solutions on SharePoint. Ben has a wealth of experience fulfilling customer requirements by using Microsoft technologies.