8 out of 22 rated this helpful - Rate this topic

ConnectWeb Parts in SharePoint 2010

SharePoint 2010

SharePoint QuickStart Banner

Getting Started with Web Parts in SharePoint 2010:  Learn to build, deploy, and connect two Web Parts together.

Applies to:  Microsoft SharePoint Server 2010 | Visual Studio 2010

Published:  April 2010 | Updated:  October 2010

Provided by:  Frank Rice, Microsoft Corporation

In this exercise, you create and deploy two Web Parts. Then you add them to a Web Parts Page and connect them so that making a selection in one Web Part displays that selection in the other Web Part. To complete this task, you must do the following:

Create a Sample Project Task List in SharePoint 2010

This exercise requires a list named Projects on the local SharePoint 2010 Web site specified later in this article. The list should contain the fields shown in Table 1. To create this list, follow these steps:

To create the Project Task List

  1. Open the SharePoint 2010 Web site that you want to add the Web Parts to (such as http://localhost/sites/SampleWebPartSite) in Internet Explorer.

  2. Click Site Actions, click More Options, and then click Custom List.

  3. In the Name box, type Projects and then click Create.

  4. On the List Tools tab, click List, and on the Manage Views group, click Modify Views.

  5. Clear all Column Name options and then select the ID and Title options. Click OK.

  6. Click Add new item and add the information in the first row (ignore the header row) of Table 1. The ID fields updates automatically.

     

    Title

    Writing more sample code

    Writing more developer tools

    Answering forum questions

    Writing developer articles

  7. Repeat step 6 for the remaining rows of Table 1.

Create a new SharePoint Empty Project

In this task, you create a SharePoint 2010 Empty project in Microsoft Visual Studio 2010.

To create the SharePoint project

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

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

  3. Click the SharePoint Empty Project project template (see Figure 1), provide a name (such as, ConnectTwoWebParts), a location for your project, and then click OK.



    Figure 1. Select the Empty SharePoint Project type

    Select the Empty SharePoint Project type
  4. In the What local site do you want to use for debugging list, select the site to use (such as http://localhost/SampleWebPage). Also select the Deploy as a farm solution option and then click Finish.

    The ConnectTwoWebParts project is created and Solution Explorer is displayed.

Create the Web Part Connection Interface

In this task, you create the Web Part connection interface IProject that is responsible for exchanging connection information between a Web Part provider and Web Part consumer.

To create the Web Part connection interface

  1. In Solution Explorer, right-click ConnectTwoWebParts, point to Add, and then click New Item.

  2. In the Add New Item dialog window, click Visual C#, click Code, and then select Interface from the available templates.

  3. Type IProject in the Name box and then click Add.

  4. In Solution Explorer, double-click the IProject.cs file.

  5. Change the visibility of the interface to public by prefixing the keyword public to the interface declaration (see Figure 2).



    Figure 2. The IProject Interface

    The IProject Interface
  6. Insert the following code inside the IProject interface.

    int Id { get; } 
    string Name { get; }
    
    

Create the Provider Web Part

In this task, you create a Web Part to participate in a Web Part connection as a provider.

To create the provider Web Part

  1. In Solution Explorer, right-click ConnectTwoWebParts, point to Add, and then click New Item.

  2. Click the Visual C# node in the Installed Templates section, click SharePoint, and then click 2010. Select Web Part from the available templates.

  3. Type ProviderWebPart in the Name box and then click Add.

    The provider Web Part is added to the project.

  4. In Solution Explorer, double-click ProviderWebPart.cs to open the code file.

  5. In the ProviderWebPart class declaration, replace the class from which the ProviderWebPart class is inheriting by changing WebPart to the following:

    Microsoft.SharePoint.WebPartPages.WebPart, IProject
    
    
  6. Insert the following code immediately after the opening bracket ({) in the ProviderWebPart class declaration. This code block implements the IProject Web Part connection interface and adds a local variable to the Web Part.

    DropDownList _projectPicker = null;  
    int IProject.Id 
    { 
        get { return int.Parse(_projectPicker.SelectedValue); } 
    } 
     
    string IProject.Name 
    { 
        get { return _projectPicker.SelectedItem.ToString(); } 
    }
    
  7. Insert the following code in the CreateChildControls subroutine.

    
    base.CreateChildControls;
    try 
    { 
        _projectPicker = new DropDownList(); 
     
        using (SPSite spSite = new SPSite(SPContext.Current.Web.Url)) 
        using (SPWeb spWeb = spSite.OpenWeb()) 
        { 
            SPList projectsList = spWeb.Lists["Projects"]; 
     
            foreach (SPListItem project in projectsList.Items) 
            { 
                _projectPicker.Items.Add(new ListItem(project.Name, project.ID.ToString())); 
            } 
        } 
        _projectPicker.AutoPostBack = true; 
     
        this.Controls.Add(_projectPicker); 
    } 
    catch (Exception ex) 
    { 
        this.Controls.Clear(); 
        this.Controls.Add(new LiteralControl(ex.Message)); 
    }
    
  8. Insert the following ConnectionProvider property after the CreateChildControls subroutine. This provides the connection provider interface point for the ProviderWebPart.

    [ConnectionProvider("Project Name and ID")] 
    public IProject NameDoesNotMatter() 
    { 
        return this; 
    }
    
  9. Delete the RenderContents subroutine, if it exists.

Create the Consumer Web Part

In this task, you create a Web Part to participate in a Web Part connection as a consumer.

To create the Consumer Web Part

  1. In Solution Explorer, right-click ConnectTwoWebParts, point to Add, and then click New Item.

  2. Click the Visual C# node in the Installed Templates section, click SharePoint, and then click 2010. Select Web Part from the available templates.

  3. Type ConsumerWebPart in the Name box and then click Add.

    The consumer Web Part is added to the project.

  4. In Solution Explorer, double-click ConsumerWebPart.cs to open the code file.

  5. Insert the following code after the opening bracket ({) of the ConsumerWebPart class declaration.

    IProject _provider = null; 
    Label _lbl = null;
    
  6. Insert the following code in the CreateChildControls subroutine.

    
    base.CreateChildControls;
    try 
    { 
        _lbl = new Label(); 
     
        if (_provider != null) 
        { 
            if (_provider.Id > 0) 
            { 
                _lbl.Text = _provider.Name + " was selected."; 
            } 
            else 
            { 
                _lbl.Text = "Nothing was selected."; 
            } 
        } 
        else 
        { 
            _lbl.Text = "No Provider Web Part Connected."; 
        } 
     
        this.Controls.Add(_lbl); 
    } 
    catch (Exception ex) 
    { 
        this.Controls.Clear(); 
        this.Controls.Add(new LiteralControl(ex.Message)); 
    }
    
  7. Insert the following ConnectionConsumer property after the CreateChildControls subroutine. This provides the connection consumer interface point for the ConsumerWebPart Web Part.

    [ConnectionConsumer("Project Name and ID")] 
    public void ThisNameDoesNotMatter(IProject providerInterface) 
    { 
        _provider = providerInterface; 
    }
    
  8. Delete the RenderContents subroutine, if it exists.

Deploy and Add the Web Parts to a Web Parts Page

In this task, you build and deploy the provider and consumer Web Parts. Then you add the Web Parts to a Web Parts page.

To deploy and add the Web Parts to a Web Parts page

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

  2. Open Internet Explorer and browse to the Web site that you specified for the project.

  3. Click the Site Actions menu and then click More Options.

  4. Scroll and then click Web Part Page. Type SampleWebPartPage in the Name box and then click Create.

    SharePoint Foundation creates the Web Parts page and opens it in Edit mode.

  5. Click one of the Web Part zones in the blue box.

  6. Select Custom in the Categories box (see Figure 3), select the ConsumerWebPart, and then click Add.



    Figure 3. Select the ConsumerWebPart

    Select the ConsumerWebPart
  7. This adds the ConsumerWebPart to the page as shown in Figure 4.



    Figure 4. The ConsumerWebPart is added to the Web Part zone

    The ConsumerWebPart is added to the Web Part zone
  8. Repeat these steps to add the ProviderWebPart to a different Web Part zone. Both Web Parts are now displayed on the page as shown in Figure 5.



    Figure 5. Both Web Parts have been added to the page

    Both Web Parts have been added to the page

Connect the Two Web Parts

In this task, you connect the Provider Web Part to the Consumer Web Part.

To connect the Web Parts

  1. In this task, you connect the Provider Web Part to the Consumer Web Part.

  2. Point to Connections, point to Send Project Name and ID To, and then click ConsumerWebPart.

    You should see the project title displayed in the ConsumerWebPart Web Part.

  3. Make a different selection in the Provider Web Part list. The change in title is then reflected in the Consumer Web Part zone as shown in Figure 6.



    Figure 6. Change in the Provider Web Part is reflected in the Consumer Web Part

    Change in the Provider Web Part is reflected

Next Steps

 
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Additional comments for my post below
Well, it has been a long road since I posted yesterday. But here is what I found. The problem I am having was two fold. 1) The following is the correct code for ECT lists: foreach (SPListItem listRecords in projectsList.Items) // add to dropdown list { ListItem tempItem = new ListItem(listRecords["name"].ToString()); ListItem tempItem2 = new ListItem(listRecords["typeID"].ToString()); _projectPicker.Items.Add(tempItem); //_projectPicker.Items.Add(new ListItem(listRecords.Name, listRecords.ID.ToString())); } This allowed me to pull the list just great! 2) I still have not figured this out, but the selectedIndex is not pulling from the dropdownlist for ECT list (it is for custom lists). When I change the code to the line below I do not get the "Input string was not in a correct format" error. Any guidance here? int IProject.typeID { get { return 1; }//int.Parse(_projectPicker.SelectedValue); } }
Great Post - But does it work with ECT?
I would like to see if I can pull data in the provider webpart from a external list in same site. I built the external list next to my custom list as "Project" and "Project2," respectively. When I change the title to the custom list everything in dropdown does great. I change the name back to external list and nothing but blanks. Is there a coding difference when using external list?
base.CreateChildControls; shows up twice change it to base.CreateChildControls();
This guide works. The only part that is bugged is the code " base.CreateChildControls; " (with out the quotation marks) it shows up TWICE. so make sure you change both of these to " base.CreateChildControls(); " (without quotation marks) 

I decided to restate this issue to let others who maybe new like me  this issue shows up twice.

Make sure you use a web part page
I answered my own question - this code only works on a web part page (Site Actions->More Options->Web Part Page).  It will not work on  a wiki page
Can't get the connections to work
I followed this example to the letter, but when I deploy the web parts, I can't get the connections to show up (I'm using visual web parts).  I think it has to do with the how the interface is designed in the example, but I can't be sure.  Has anyone else had this problem?
Can we connect two web parts on different pages
I would like to connect two web parts on different pages. If I change the first webpart and go to the second page, it shoud display the content related to the first webpart selection. Is it possible?
Example Code Error
After following the example I am getting the error below when I try to deploy.  I have made the Interface public and entered the brackets after base.CreateChildControls. $0$0 $0 $0 $0Error1'ConnectTwoWebParts.ProviderWebPart.ProviderWebPart' does not implement interface member 'ConnectTwoWebParts.IProject.Id'C:\SPSTraining\Projects\ConnectTwoWebParts\ConnectTwoWebParts\ProviderWebPart\ProviderWebPart.cs$0 $0 $0$0 $0 $0Any suggestions would be appreciated.$0
How to connect the two web parts?
where can I the Connections mentioned in the last step??

To See Connections, first the page should be in Edit mode.
Then click the Webpart menu, you will see Connections below Edit Web Part.
help with this message
gives me this error:

List 'Projects' does not exist at site with URL ............

some help?
Some tutorials
$0SharePoint Interview Questions on SharePoint$0 $0http://www.fewlines4biju.com/search/label/Interview%20Questions$0 $0$0 $0 $0SharePoint 2010 Tutorials$0 $0http://www.fewlines4biju.com/search/label/SharePoint%202010$0 $0$0 $0 $0Jobs$0 $0http://www.fewlines4biju.com/search/label/Jobs$0 $0$0 $0 $0Personal Blogs$0 $0http://www.fewlines4biju.com/search/label/Personal$0 $0$0 $0 $0A SharePoint and Personal blog on sharepoint 2010, wss, moss 2007, interview questions and jobs, C#.Net, Asp.net, Sql Server,$0 $0http://www.fewlines4biju.com$0
don't bother with this sample, it's broken in sandbox
After many frustrating hours, and a web tour of sharepoint info, I found that the "Microsoft.SharePoint.WebPartPages.WebPart" is not allowed within the new sharepoint sandbox.  Consequently, I think that the connection mechanism is broken.  Most of the suggestions that I've found focus on using external data source solutions instead, to avoid the sandbox constraints.
Clarity on a few staff
Visual studio does'nt put the "Public" infront of the IProject interface,
This will affect your the following methods:
      public  IProject NameDoesNotMatter(){return this;}  from the provider webpart and the 
      public void ThisNameDoesNotMatter(IProject ProviderInterface) {_Provider = ProviderInterface;} from the consumer webpart
Because the interface will not be accessible, you can add the "public" manually in code.
And onother thing  visual studio will complain about the following statements
 base.CreateChildControls and
the base.CreateChildControls
Making them method calls by including "()" at the end will solve thw problem.

Cannot connect parts on different pages
Add Consumer part to another page, can't create the connection from Provider :-(
base.CreateChildcontrols(); cant be added in the createchildcontrols.
base.CreateChildcontrols(); cant be added in the createchildcontrols.

Error    1    'System.Web.UI.WebControls.WebParts.WebPart' does not contain a definition for 'CreateChildcontrols'    k:\users\administrator\documents\visual studio 2010\Projects\SlnWebParts\SlnWebParts\WebPartProvider\WebPartProvider.cs    30    18    SlnWebParts

RK: .NET is case sensitive. You have to say CreateChildControls, not CreateChildcontrols.

----------------

Add the brackets ont he end for the compilation error - base.CreateChildcontrols();  in the example it is: base.CreateChildcontrols

Bill Irvine
base.CreateChildcontrols issue
The issue with the CreateChildControls comilation error is just that it should be CreateChildControls() ... ie: add the brackets.

Bill Irvine
There are 2 types of SharePoint 2010 Webpart
If you are stepping through the code make sure you create a SharePoint Visual Web Part rather than a C# WebPart