Connecting web parts the easy wayExactly one year ago (and wow I did not time this!) I posted a blog about “Connecting a web part with a standard SharePoint list”. For my current project I had to develop 2 web parts that could connect with each other.

Since Moss2007 you can implement your own connection interface which enables you to connect customized web parts. It looks like you can basically transfer any serializable information.

The first thing you have to do is to define a very simple interface. The second step is to inherit the interface at the web part class that sends the information. In this class you’ll have to assign the interface as the connection interface. The last step in the provider web part is to include the “get function” described by the interface to pass the value.

In our consumer web part we have to retrieve the connection interface. Once this connection has been setup we can read and use the given value.

In the example code we will use the interface with the name “IMossStringConnection” to pass a string value.

Our web part and interface that provides our custom value:

namespace Sample.Code
{
 ///
 /// Our custom interface
 ///

 public interface IMossStringConnection
 {
  string ProvidedString { get;}
 }

 ///

 /// Web Part Class
 ///

 public class ProviderWebPart : WebPartBase, IMossStringConnection
 {
  ….WEB PART CODE….

  //We start our connection provider here. The property name is the name
  SharePoint will show in the connection menu (Called UserID in our image
  example).
  [ConnectionProvider(“PropertyName”)]
  public IMossStringConnection ConnectionInterface()
  {
    return this;
  }

  //function to provide our value
  public string ProvidedString
  {
   get
   {
     return “Example value”;
   }
  }
 }
}

The web part shows the property name (UserID) in the connection menu.

And here is the code for the web part that consumes the provided value:

namespace Sample.Code
{
 ///
 /// Web Part to consume the value
 ///

 public class ConsumerWebPart : WebPartBase
 {
  ….WEB PART CODE….

  IMossStringConnection m_providerPart = null;

  ///

  /// Encapsulate the interface
  ///

  public IMossStringConnection ProviderPart
  {
   get { return m_providerPart; }
   set { m_providerPart = value; }
  }

  //We start our connection consumer here. The property name is the name
  SharePoint will show in the connection menu (Called UserID in our image
  example).
  [ConnectionConsumer(“Property”)]
  public void GetConnectionInterface(IMossStringConnection providerPart)
  {
   ProviderPart = providerPart;
   //Now we can retrieve the value of the other web part
   string retrieveValue = ProviderPart.ProvidedString;
  }
 }
}

And that’s basically all the code you need to implement. Just copy and paste it in your web parts and have some fun!