Connecting Visual Web Parts

Connecting web parts is usually quite easy and straight forward. But if you want to connect a visual web part and access the data from the connection provider in the user control of your visual web part, it might get complicated.

The problem is the different web part life cycles when first loading the web part and after the post back of the web part. Because when you load the page the first time, the web part connection is available in the CreateChildControls method, when you create your user control and you can pass the data to the user control. But as soon as you post back, the connection providers are not available in CreateChildControls but later in PreRender.

Moving the user control creation into PreRender is not possible because that’s to late for event registration, so that buttons and so on won’t work in the user control.

 

The right approach:

Create a property for the web part in your user control and pass the web part to the user control in the CreateChildControls of the web part. Doing this, you can access webpart.connectionProvider from your user control!

 

 

Web part code:

public class MyWebpart : WebPart
{
     private const string _ascxPath = @”…”;
 
     protected override void CreateChildControls()#
     {
         MyConsumerUserControl control = Page.LoadControl(_ascxPath) as MyWebpartUserControl;
         control.WebPart = this;
         Controls.Add(control);
     }
 
     public int Data { get; set; }
     [ConnectionConsumer(“ProviderInterface”)]
     public void SetData(IProvider provider)
     {
         if (Data != null)
         {
             this.Data = provider.Data;
         }
     }
}

 

User control code:

public partial class MyWebpartUserControl : UserControl
{
     public MyWebpart WebPart { get; set; }
     
     protected override void OnPreRender(EventArgs e)
     {
         base.OnPreRender(e);
         this.Label1.Text = this.WebPart.Data.ToString();
     }
}

Leave a Reply

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

*