Connecting web parts programmatically

We need SPLimitedWebPartManager to connect the Web parts with ASP.NET style interfaces. The steps for this are:

  1. Get the SPLimitedWebPartManager instance on the page;
  2. Get the provider and consumer Web parts need to be connected;
  3. Get the connection points for the provider and consumer Web parts;
  4. Connect them using SPConnectWebParts method. If necessary, certain transforming needs to be in place for compatible interfaces
SPWeb web = (SPWeb)properties.Feature.Parent;      
SPLimitedWebPartManager mgr = web.GetLimitedWebPartManager("default.aspx", PersonalizationScope.Shared);      
System.Web.UI.WebControls.WebParts.WebPart provider= mgr.WebParts["Provider"];   
System.Web.UI.WebControls.WebParts.WebPart consumer= mgr.WebParts["Consumer"];  
ConsumerConnectionPoint addConsumerConnPoint = mgr.GetConsumerConnectionPoints(consumer)["AddressConsumer_ot"];   
ProviderConnectionPoint addProviderConnPoint = mgr.GetProviderConnectionPoints(provider)["AddressProvider_ot"];      
mgr.SPConnectWebParts(provider, addProviderConnPoint, consumer, addConsumerConnPoint);

1 thought on “Connecting web parts programmatically”

  1. Thanks for this useful snippet. I'm trying to implement this in the same method that I'm using to add webparts using manager.AddWebPart, however, I'm getting an error saying that the webpart does not exist on the page.

    ConsumerConnectionPoint addConsumerConnPoint = mgr.GetConsumerConnectionPoints(wptitle)["wptitle"];
    ProviderConnectionPoint addProviderConnPoint = mgr.GetProviderConnectionPoints(provider)["provider"];
    mgr.SPConnectWebParts(provider, addProviderConnPoint, wptitle, addConsumerConnPoint);

    The provider is a webpart called WPCategoryProvider, aliased as provider here, and the Consumer is WPCategoryTitle aliased as wptitle.

    Have I got the correct code in place, and if so could you explain what method I should place it on. I'm provisioning the webparts to a Page Layout, so that a page populated with webparts and connected to the provider is created when someone creates a new page through my feature. The code is currently in CreateCategoryPage.aspx (inline) which is the feature they create the page in. My page layout is wfCategory.aspx.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.