Monday, October 15, 2012

Connected Web Parts

SharePoint Object Model provides the functionality where web parts can communicate with each others by sending and getting parameters and this mechanism is called Connected Web Parts. You can create connections between web parts and send/receive information between them.

In this post i am going to explain how you can make connection between web parts pro-grammatically.

The connected web parts is based on the concept of interface.

First of all creates a interface and a property whose value can be send to other web parts. In my case i have created a property to send client info to other web part 

  public interface ClientInterface
    {
        string clientinfo { get; }

    }
Now create a web part from say "SenderSenderWebPart " where you want to send the value to other web part and inherit above interface like

 public class SenderWebPart : WebPart,ClientInterface
    
Now create a property to send the value in this web part

 public string clientinfo
        {

            get
            {
                return "Your Test Value";
            }
        }

and create a connection attribute like below:

[ConnectionProvider("clientinfoprovider")]
        public ClientInterface getclientname()
        {
            return this;
        }

Now create another web part say "Receiver" that will receive this clientinfo from above web part

Create a object of interface in this new web part like   ClientInterface clientinfostring;

Create a connection consumer attribute like 

[ConnectionConsumer("clientinforRightNavigationWebpart", "GetClientInfo")]
        public void ReceiveClientInfo(ClientInterface c)
        {
            clientinfostring = c;
        }

Now you can get the clientinfo in this web part. 

For example 

 protected override void RenderContents(HtmlTextWriter writer)
        {

      
            if (clientinfostring != null)
            {

                 string clientname= clientinfostring.clientinfo;
              
                writer.Write(clientname);
            }

Now build and deploy the web parts. When you place these web parts on page, select edit page, edit sender web part, select connection and make connection to the receiver web part as shown below







Once you create a connection it ask for the confirmation. Now your web parts are connected and can communicate with each other.

No comments:

Post a Comment