Partager via


Walkthrough: Creating a Web Part for SharePoint

Web Parts enable users to directly modify the content, appearance, and behavior of SharePoint site pages by using a browser. This walkthrough shows you how to create a Web Part by using the Web Part item template in Visual Studio 2010.

The Web Part displays employees in a data grid. The user specifies the location of the file that contains the employee data. The user can also filter the data grid so that employees who are managers appear in the list only.

This walkthrough illustrates the following tasks:

  • Creating a Web Part by using the Visual Studio Web Part item template.

  • Creating a property that can be set by the user of the Web Part. This property specifies the location of the employee data file.

  • Rendering content in a Web Part by adding controls to the Web Part controls collection.

  • Creating a new menu item, referred to as a verb, that appears in the verbs menu of the rendered Web part. Verbs enable the user to modify the data that appears in the Web Part.

  • Testing the Web Part in SharePoint.

    Note

    Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Customizing Development Settings in Visual Studio.

Prerequisites

You need the following components to complete this walkthrough:

Creating an Empty SharePoint Project

First, create a Empty SharePoint project. Later, you will add a Web Part to the project by using the Web Part item template.

To create an Empty SharePoint Project

  1. Start Visual Studio by using the Run as Administrator option.

  2. On the men bar, choose File, New, Project.

  3. In the New Project dialog box, expand the SharePoint node under the language that you want to use, and then choose the 2010 node.

  4. In the Templates pane, choose SharePoint 2010 Project, and then choose the OK button.

    The SharePoint Customization Wizard appears. This wizard enables you to select the site that you will use to debug the project and the trust level of the solution.

  5. Choose the Deploy as a farm solution option button, and then choose the Finish button to accept the default local SharePoint site.

Adding a Web Part to the Project

Add a Web Part item to the project. The Web Part item adds the Web Part code file. Later, you will add code to the Web Part code file to render the contents of the Web Part.

To add a Web Part to the Project

  1. On the menu bar, choose Project, Add New Item.

  2. In the Add New Item dialog box, in the Installed Templates pane, expand the SharePoint node, and then choose the 2010 node.

  3. In the list of SharePoint templates, choose the Web Part template, and then choose the Add button.

    The Web Part item appears in Solution Explorer.

Rendering Content in the Web Part

You can specify which controls you want to appear in the Web Part by adding them to the controls collection of the Web Part class.

To render content in the Web Part

  1. In Solution Explorer, open WebPart1.vb (in Visual Basic) or WebPart1.cs (in C#).

    The Web Part code file opens in Code Editor.

  2. Add the following statements to the top of the Web Part code file.

    Imports System.Data
    
    using System.Data;
    
  3. Add the following code to the WebPart1 class. This code declares the following fields:

    • A data grid to display employees in the Web Part.

    • Text that appears on the control that is used to filter the data grid.

    • A label that displays an error if the data grid is unable to display data.

    • A string that contains the path of the employee data file.

    Private grid As DataGrid
    Private Shared verbText As String = "Show Managers Only" 
    Private errorMessage As New Label()
    Protected xmlFilePath As String
    
    private DataGrid grid;
    private static string verbText = "Show Managers Only";
    private Label errorMessage = new Label();
    protected string xmlFilePath;
    
  4. Add the following code to the WebPart1 class. This code adds a custom property named DataFilePath to the Web Part. A custom property is a property that can be set in SharePoint by the user. This property gets and sets the location of a XML data file that is used to populate the data grid.

    <Personalizable(PersonalizationScope.[Shared]), _
        WebBrowsable(True), WebDisplayName("Path to Employee Data File"), _
        WebDescription("Location of the XML file that contains employee data")> _
    Public Property DataFilePath() As String 
        Get 
            Return xmlFilePath
        End Get 
        Set(ByVal value As String)
            xmlFilePath = value
        End Set 
    End Property
    
    [Personalizable(PersonalizationScope.Shared), WebBrowsable(true),
    WebDisplayName("Path to Employee Data File"),
    WebDescription("Location of the XML file that contains employee data")]
    public string DataFilePath
    {
        get
        {
            return xmlFilePath;
        }
        set
        {
            xmlFilePath = value;
        }
    }
    
  5. Replace the CreateChildControls method with the following code. This code performs the following tasks:

    • Adds the data grid and label that you declared in the previous step.

    • Binds the data grid to an XML file that contains employee data.

    Protected Overloads Overrides Sub CreateChildControls()
    
        'Define the grid control that displays employee data in the Web Part.
        grid = New DataGrid()
        With grid
            .Width = Unit.Percentage(100)
            .GridLines = GridLines.Horizontal
            .HeaderStyle.CssClass = "ms-vh2"
            .CellPadding = 2
            .BorderWidth = Unit.Pixel(5)
            .HeaderStyle.Font.Bold = True
            .HeaderStyle.HorizontalAlign = HorizontalAlign.Center
        End With 
    
    
    
        'Populate the grid control with data in the employee data file. 
        Try 
            Dim dataset As New DataSet()
            dataset.ReadXml(xmlFilePath, XmlReadMode.InferSchema)
            grid.DataSource = dataset
            grid.DataBind()
        Catch x As Exception
            errorMessage.Text += x.Message
        End Try 
    
        'Add control to the controls collection of the Web Part.
        Controls.Add(grid)
        Controls.Add(errorMessage)
        MyBase.CreateChildControls()
    
    End Sub
    
    protected override void CreateChildControls()
    {
        // Define the grid control that displays employee data in the Web Part.
        grid = new DataGrid();
        grid.Width = Unit.Percentage(100);
        grid.GridLines = GridLines.Horizontal;
        grid.HeaderStyle.CssClass = "ms-vh2";
        grid.CellPadding = 2;
        grid.BorderWidth = Unit.Pixel(5);
        grid.HeaderStyle.Font.Bold = true;
        grid.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
    
        // Populate the grid control with data in the employee data file. 
        try
        {
            DataSet dataset = new DataSet();
            dataset.ReadXml(xmlFilePath, XmlReadMode.InferSchema);
            grid.DataSource = dataset;
            grid.DataBind();
        }
        catch (Exception x)
        {
            errorMessage.Text += x.Message;
        }
    
        // Add control to the controls collection of the Web Part.
        Controls.Add(grid);
        Controls.Add(errorMessage);
        base.CreateChildControls();
    }
    
  6. Add the following method to the WebPart1 class. This code performs the following tasks:

    • Creates a verb that appears in the Web Part verbs menu of the rendered Web part.

    • Handles the event that is raised when the user chooses the verb in the verbs menu. This code filters the list of employees that appears in the data grid.

    Public Overrides ReadOnly Property Verbs() As WebPartVerbCollection
        Get 
            Dim customVerb As New WebPartVerb("Manager_Filter_Verb", _
                New WebPartEventHandler(AddressOf CustomVerbEventHandler))
    
            customVerb.Text = verbText
            customVerb.Description = "Shows only employees that are managers" 
    
            Dim newVerbs() As WebPartVerb = {customVerb}
    
            Return New WebPartVerbCollection(MyBase.Verbs, newVerbs)
        End Get 
    End Property 
    
    Protected Sub CustomVerbEventHandler(ByVal sender As Object, ByVal args As WebPartEventArgs)
        Dim titleColumn As Integer = 2
    
        Dim item As DataGridItem
        For Each item In grid.Items
            If item.Cells(titleColumn).Text <> "Manager" Then 
                If item.Visible = True Then
                    item.Visible = False 
                Else
                    item.Visible = True 
                End If 
            End If 
        Next item
        If verbText = "Show Managers Only" Then
            verbText = "Show All Employees" 
        Else
            verbText = "Show Managers Only" 
        End If 
    End Sub
    
    public override WebPartVerbCollection Verbs
    {
        get
        {
            WebPartVerb customVerb = new WebPartVerb("Manager_Filter_Verb",
                new WebPartEventHandler(CustomVerbEventHandler));
    
            customVerb.Text = verbText;
            customVerb.Description = "Shows only employees that are managers";
    
            WebPartVerb[] newVerbs = new WebPartVerb[] { customVerb };
    
            return new WebPartVerbCollection(base.Verbs, newVerbs);
        }
    }
    
    protected void CustomVerbEventHandler(object sender, WebPartEventArgs args)
    {
        int titleColumn = 2;
    
        foreach (DataGridItem item in grid.Items)
        {
            if (item.Cells[titleColumn].Text != "Manager")
            {
                if (item.Visible == true)
                {
                    item.Visible = false;
                }
                else
                {
                    item.Visible = true;
                }
            }
    
        }
        if (verbText == "Show Managers Only")
        {
            verbText = "Show All Employees";
        }
        else
        {
            verbText = "Show Managers Only";
        }
    }
    

Testing the Web Part

When you run the project, the SharePoint site opens. The Web Part is automatically added to the Web Part Gallery in SharePoint. You can add the Web Part to any Web Part page.

To test the Web Part

  1. Paste the following XML into a Notepad file. This XML file contains the sample data that will appear in the Web Part.

    <?xml version="1.0" encoding="utf-8" ?>
        <employees xmlns="https://schemas.microsoft.com/vsto/samples">
           <employee>
               <name>David Hamilton</name>
               <hireDate>2001-05-11</hireDate>
               <title>Sales Associate</title>
           </employee>
           <employee>
               <name>Karina Leal</name>
               <hireDate>1999-04-01</hireDate>
               <title>Manager</title>
           </employee>
           <employee>
               <name>Nancy Davolio</name>
               <hireDate>1992-05-01</hireDate>
               <title>Sales Associate</title>
           </employee>
           <employee>
               <name>Steven Buchanan</name>
               <hireDate>1955-03-04</hireDate>
               <title>Manager</title>
           </employee>
           <employee>
               <name>Suyama Michael</name>
               <hireDate>1963-07-02</hireDate>
               <title>Sales Associate</title>
           </employee>
        </employees>
    
  2. In Notepad, on the menu bar, choose File, Save As.

  3. In the Save As dialog box, in the Save as type list, choose All Files.

  4. In the File name box, enter data.xml.

  5. Choose any folder by using the Browse Folders button, and then choose the Save button.

  6. In Visual Studio, choose the F5 key.

    The SharePoint site opens.

  7. On the Site Actions menu, choose More Options.

  8. In the Create page, choose the Web Part Page type, then choose the Create button.

  9. In the New Web Part Page page, name the page SampleWebPartPage.aspx, and then choose the Create button.

    The Web Part page appears.

  10. Select any zone on the Web Part page.

  11. At the top of the page, choose the Insert tab, and then choose the Web Part button.

  12. In the Categories pane, choose the Custom folder, choose the WebPart1 Web Part, and then choose the Add button.

    The Web Part appears on the page.

Testing the Custom Property

To populate the data grid that appears in the Web Part, specify the path of the XML file that contains data about each employee.

To test the custom property

  1. Choose the arrow that appears on the right side of the Web Part, and then choose Edit Web Part from the menu that appears.

    A pane that contains properties for the Web Part appears on the right side of the page.

  2. In the pane, expand the Miscellaneous node, enter the path of the XML file that you created earlier, choose the Apply button, and then choose the OK button.

    Verify that a list of employees appears in the Web Part.

Testing the Web Part Verb

Show and hide employees that are not managers by clicking an item that appears in the Web Part verbs menu.

To test the Web Part verb

  1. Choose the arrow that appears on the right side of the Web Part, and then choose Show Managers Only from the menu that appears.

    Only employees who are managers appear in the Web Part.

  2. Choose the arrow again, and then choose Show All Employees from the menu that appears.

    All employees appear in the Web Part.

See Also

Tasks

How to: Create a SharePoint Web Part

How to: Create a SharePoint Web Part by Using a Designer

Walkthrough: Creating a Web Part for SharePoint by Using a Designer

Other Resources

Creating Web Parts for SharePoint