In certain situation we need to pass data from webpart to another webpart present in the same site. To implement the connection functionality between WebParts, we should create an Interface .This interface will be implemented by both the provider and consumer classes.
Then we will use the ConnectionProvider and ConnectionConsumer attribute to make the connection between the two webpart.
EXAMPLE:
1. Interface : public interface Test { string Name { get; set; } }
2. The provider class :
public class Provider : WebPart, Test { TextBox tb = new TextBox(); Button btn = new Button(); string _Name = ""; public string Name { get{return _Name;} set{_Name = value;} } protected override void CreateChildControls() { btn.Text = "Show"; btn.Click += new EventHandler(btn_Click); tb.Text = "Prem"; Name = tb.Text; this.Controls.Add(tb); this.Controls.Add(btn); } protected override void Render(HtmlTextWriter writer) { EnsureChildControls(); RenderChildren(writer); } void btn_Click(object sender, EventArgs e) { Name = tb.Text; } [ConnectionProvider("Test Provider")] public Test ProvideCommunication() { return this as Test; } }
3.The consumer class:
public class Consumer : WebPart { private Test providerWebPart; [ConnectionConsumer("Test Consumer")] public void ReceiveName(Test provider) { providerWebPart = provider; } protected override void Render(HtmlTextWriter writer) { if (providerWebPart != null) writer.Write("Value provided is : " + providerWebPart.Name); base.Render(writer); } }
When the button is clicked the value for the Name is set. Then the current instance of the interface is pass to consumer webpart. The ReceiveName Method will act as a receiver of the Test interface.