Bewerken

Delen via


WebPartConnection Class

Definition

Provides an object that enables two WebPart controls to form a connection. This class cannot be inherited.

public ref class WebPartConnection sealed
[System.ComponentModel.TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))]
public sealed class WebPartConnection
[<System.ComponentModel.TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))>]
type WebPartConnection = class
Public NotInheritable Class WebPartConnection
Inheritance
WebPartConnection
Attributes

Examples

The following code example demonstrates how to create a simple connection between two WebPart controls. The example demonstrates three ways of forming a connection: declaratively, by placing tags for the connection in the markup of the Web page; programmatically, by creating the connection in code; and through the UI, by placing a ConnectionsZone control on the page, which enables users to establish a connection.

The code example has four parts:

  • A user control that enables you to change the Web Parts display mode on a page.

  • Source code for an interface and two WebPart controls acting as the provider and the consumer for a connection.

  • A Web page to host all the controls and run the code example.

  • An explanation of how to run the example page.

The first part of this code example is the user control that enables users to change display modes on a Web page. Save the following source code to an .ascx file, giving it the file name that is assigned to the Src attribute of the Register directive for this user control, which is near the top of the hosting Web page. For details about display modes and a description of the source code in this control, see Walkthrough: Changing Display Modes on a Web Parts Page.

<%@ control language="C#" classname="DisplayModeMenuCS"%>
<script runat="server">
  
 // Use a field to reference the current WebPartManager.
  WebPartManager _manager;

  void Page_Init(object sender, EventArgs e)
  {
    Page.InitComplete += new EventHandler(InitComplete);
  }  

  void InitComplete(object sender, System.EventArgs e)
  {
    _manager = WebPartManager.GetCurrentWebPartManager(Page);

    String browseModeName = WebPartManager.BrowseDisplayMode.Name;

    // Fill the dropdown with the names of supported display modes.
    foreach (WebPartDisplayMode mode in _manager.SupportedDisplayModes)
    {
      String modeName = mode.Name;
      // Make sure a mode is enabled before adding it.
      if (mode.IsEnabled(_manager))
      {
        ListItem item = new ListItem(modeName, modeName);
        DisplayModeDropdown.Items.Add(item);
      }
    }

    // If shared scope is allowed for this user, display the scope-switching
    // UI and select the appropriate radio button for the current user scope.
    if (_manager.Personalization.CanEnterSharedScope)
    {
      Panel2.Visible = true;
      if (_manager.Personalization.Scope == PersonalizationScope.User)
        RadioButton1.Checked = true;
      else
        RadioButton2.Checked = true;
    }
    
  }
 
  // Change the page to the selected display mode.
  void DisplayModeDropdown_SelectedIndexChanged(object sender, EventArgs e)
  {
    String selectedMode = DisplayModeDropdown.SelectedValue;

    WebPartDisplayMode mode = _manager.SupportedDisplayModes[selectedMode];
    if (mode != null)
      _manager.DisplayMode = mode;
  }

  // Set the selected item equal to the current display mode.
  void Page_PreRender(object sender, EventArgs e)
  {
    ListItemCollection items = DisplayModeDropdown.Items;
    int selectedIndex = 
      items.IndexOf(items.FindByText(_manager.DisplayMode.Name));
    DisplayModeDropdown.SelectedIndex = selectedIndex;
  }

  // Reset all of a user's personalization data for the page.
  protected void LinkButton1_Click(object sender, EventArgs e)
  {
    _manager.Personalization.ResetPersonalizationState();
  }

  // If not in User personalization scope, toggle into it.
  protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
  {
    if (_manager.Personalization.Scope == PersonalizationScope.Shared)
      _manager.Personalization.ToggleScope();
  }

  // If not in Shared scope, and if user is allowed, toggle the scope.
  protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
  {
    if (_manager.Personalization.CanEnterSharedScope && 
        _manager.Personalization.Scope == PersonalizationScope.User)
      _manager.Personalization.ToggleScope();
  }
</script>
<div>
  <asp:Panel ID="Panel1" runat="server" 
    Borderwidth="1" 
    Width="230" 
    BackColor="lightgray"
    Font-Names="Verdana, Arial, Sans Serif" >
    <asp:Label ID="Label1" runat="server" 
      Text=" Display Mode" 
      Font-Bold="true"
      Font-Size="8"
      Width="120" 
      AssociatedControlID="DisplayModeDropdown"/>
    <asp:DropDownList ID="DisplayModeDropdown" runat="server"  
      AutoPostBack="true" 
      Width="120"
      OnSelectedIndexChanged="DisplayModeDropdown_SelectedIndexChanged" />
    <asp:LinkButton ID="LinkButton1" runat="server"
      Text="Reset User State" 
      ToolTip="Reset the current user's personalization data for the page."
      Font-Size="8" 
      OnClick="LinkButton1_Click" />
    <asp:Panel ID="Panel2" runat="server" 
      GroupingText="Personalization Scope"
      Font-Bold="true"
      Font-Size="8" 
      Visible="false" >
      <asp:RadioButton ID="RadioButton1" runat="server" 
        Text="User" 
        AutoPostBack="true"
        GroupName="Scope" OnCheckedChanged="RadioButton1_CheckedChanged" />
      <asp:RadioButton ID="RadioButton2" runat="server" 
        Text="Shared" 
        AutoPostBack="true"
        GroupName="Scope" 
        OnCheckedChanged="RadioButton2_CheckedChanged" />
    </asp:Panel>
  </asp:Panel>
</div>
<%@ control language="vb" classname="DisplayModeMenuVB"%>
<script runat="server">
  ' Use a field to reference the current WebPartManager.
  Dim _manager As WebPartManager

  Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs)
    AddHandler Page.InitComplete, AddressOf InitComplete
  End Sub

  Sub InitComplete(ByVal sender As Object, ByVal e As System.EventArgs)
    _manager = WebPartManager.GetCurrentWebPartManager(Page)
      
    Dim browseModeName As String = WebPartManager.BrowseDisplayMode.Name
      
    ' Fill the dropdown with the names of supported display modes.
    Dim mode As WebPartDisplayMode
    For Each mode In _manager.SupportedDisplayModes
      Dim modeName As String = mode.Name
      ' Make sure a mode is enabled before adding it.
      If mode.IsEnabled(_manager) Then
        Dim item As New ListItem(modeName, modeName)
        DisplayModeDropdown.Items.Add(item)
      End If
    Next mode
      
    ' If shared scope is allowed for this user, display the scope-switching
    ' UI and select the appropriate radio button for the current user scope.
    If _manager.Personalization.CanEnterSharedScope Then
      Panel2.Visible = True
      If _manager.Personalization.Scope = PersonalizationScope.User Then
        RadioButton1.Checked = True
      Else
        RadioButton2.Checked = True
      End If
    End If
   
  End Sub

  ' Change the page to the selected display mode.
  Sub DisplayModeDropdown_SelectedIndexChanged(ByVal sender As Object, _
    ByVal e As EventArgs)
    
    Dim selectedMode As String = DisplayModeDropdown.SelectedValue   
    Dim mode As WebPartDisplayMode = _
      _manager.SupportedDisplayModes(selectedMode)
    If Not (mode Is Nothing) Then
      _manager.DisplayMode = mode
    End If

  End Sub
   
  ' Set the selected item equal to the current display mode.
  Sub Page_PreRender(ByVal sender As Object, ByVal e As EventArgs)
    Dim items As ListItemCollection = DisplayModeDropdown.Items
    Dim selectedIndex As Integer = _
      items.IndexOf(items.FindByText(_manager.DisplayMode.Name))
    DisplayModeDropdown.SelectedIndex = selectedIndex

  End Sub

  ' Reset all of a user's personalization data for the page.
  Protected Sub LinkButton1_Click(ByVal sender As Object, _
    ByVal e As EventArgs)
    
    _manager.Personalization.ResetPersonalizationState()
    
  End Sub

  ' If not in User personalization scope, toggle into it.
  Protected Sub RadioButton1_CheckedChanged(ByVal sender As Object, _
    ByVal e As EventArgs)
    
    If _manager.Personalization.Scope = PersonalizationScope.Shared Then
      _manager.Personalization.ToggleScope()
    End If

  End Sub
   
  ' If not in Shared scope, and if user is allowed, toggle the scope.
  Protected Sub RadioButton2_CheckedChanged(ByVal sender As Object, _
    ByVal e As EventArgs)
    
    If _manager.Personalization.CanEnterSharedScope AndAlso _
      _manager.Personalization.Scope = PersonalizationScope.User Then
      _manager.Personalization.ToggleScope()
    End If

  End Sub

</script>
<div>
  <asp:Panel ID="Panel1" runat="server" 
    Borderwidth="1" 
    Width="230" 
    BackColor="lightgray"
    Font-Names="Verdana, Arial, Sans Serif" >
    <asp:Label ID="Label1" runat="server" 
      Text=" Display Mode" 
      Font-Bold="true"
      Font-Size="8"
      Width="120" 
      AssociatedControlID="DisplayModeDropdown"/>
    <asp:DropDownList ID="DisplayModeDropdown" runat="server"  
      AutoPostBack="true" 
      Width="120"
      OnSelectedIndexChanged="DisplayModeDropdown_SelectedIndexChanged" />
    <asp:LinkButton ID="LinkButton1" runat="server"
      Text="Reset User State" 
      ToolTip="Reset the current user's personalization data for the page."
      Font-Size="8" 
      OnClick="LinkButton1_Click" />
    <asp:Panel ID="Panel2" runat="server" 
      GroupingText="Personalization Scope"
      Font-Bold="true"
      Font-Size="8" 
      Visible="false" >
      <asp:RadioButton ID="RadioButton1" runat="server" 
        Text="User" 
        AutoPostBack="true"
        GroupName="Scope" OnCheckedChanged="RadioButton1_CheckedChanged" />
      <asp:RadioButton ID="RadioButton2" runat="server" 
        Text="Shared" 
        AutoPostBack="true"
        GroupName="Scope" 
        OnCheckedChanged="RadioButton2_CheckedChanged" />
    </asp:Panel>
  </asp:Panel>
</div>

The second part of the code example is the source code for the interface and controls. The source file contains a simple interface named IZipCode. There is also a WebPart class named ZipCodeWebPart that implements the interface and acts as the provider control. Its ProvideIZipCode method is the callback method that implements the interface's only member. The method simply returns an instance of the interface. Note that the method is marked with a ConnectionProvider attribute in its metadata. This is the mechanism for identifying the method as the callback method for the provider's connection point. The other WebPart class is named WeatherWebPart, and it acts as the consumer for the connection. This class has a method named GetZipCode that gets an instance of the IZipCode interface from the provider control. Note that this method is marked as the consumer's connection point method with a ConnectionConsumer attribute in its metadata.

For the code example to run, you must compile this source code. You can compile it explicitly and put the resulting assembly in your Web site's Bin folder or the global assembly cache. Alternatively, you can put the source code in your site's App_Code folder, where it will be dynamically compiled at run time. This code example uses dynamic compilation. For a walkthrough that demonstrates how to compile, see Walkthrough: Developing and Using a Custom Web Server Control.

namespace Samples.AspNet.CS.Controls
{
  using System;
  using System.Web;
  using System.Web.Security;
  using System.Security.Permissions;
  using System.Web.UI;
  using System.Web.UI.WebControls;
  using System.Web.UI.WebControls.WebParts;

  [AspNetHostingPermission(SecurityAction.Demand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  [AspNetHostingPermission(SecurityAction.InheritanceDemand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  public interface IZipCode
  {
    string ZipCode { get; set;}
  }

  [AspNetHostingPermission(SecurityAction.Demand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  [AspNetHostingPermission(SecurityAction.InheritanceDemand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  public class ZipCodeWebPart : WebPart, IZipCode
  {
    string zipCodeText = String.Empty;
    TextBox input;
    Button send;

    public ZipCodeWebPart()
    {
    }

    // Make the implemented property personalizable to save 
    // the Zip Code between browser sessions.
    [Personalizable()]
    public virtual string ZipCode
    {
      get { return zipCodeText; }
      set { zipCodeText = value; }
    }

    // This is the callback method that returns the provider.
    [ConnectionProvider("Zip Code Provider", "ZipCodeProvider")]
    public IZipCode ProvideIZipCode()
    {
      return this;
    }

    protected override void CreateChildControls()
    {
      Controls.Clear();
      input = new TextBox();
      this.Controls.Add(input);
      send = new Button();
      send.Text = "Enter 5-digit Zip Code";
      send.Click += new EventHandler(this.submit_Click);
      this.Controls.Add(send);
    }

    private void submit_Click(object sender, EventArgs e)
    {
      if (!string.IsNullOrEmpty(input.Text))
      {
        zipCodeText = Page.Server.HtmlEncode(input.Text);
        input.Text = String.Empty;
      }
    }
  }

  [AspNetHostingPermission(SecurityAction.Demand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  [AspNetHostingPermission(SecurityAction.InheritanceDemand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  public class WeatherWebPart : WebPart
  {
    private IZipCode _provider;
    string _zipSearch;
    Label DisplayContent;

    // This method is identified by the ConnectionConsumer 
    // attribute, and is the mechanism for connecting with 
    // the provider. 
    [ConnectionConsumer("Zip Code Consumer", "ZipCodeConsumer")]
    public void GetIZipCode(IZipCode Provider)
    {
      _provider = Provider;
    }
    
    protected override void OnPreRender(EventArgs e)
    {
      EnsureChildControls();

      if (this._provider != null)
      {
        _zipSearch = _provider.ZipCode.Trim();
        DisplayContent.Text = "My Zip Code is:  " + _zipSearch;
      }
    }

    protected override void CreateChildControls()
    {
      Controls.Clear();
      DisplayContent = new Label();
      this.Controls.Add(DisplayContent);
    }
  }
}
Imports System.Web
Imports System.Web.Security
Imports System.Security.Permissions
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts

Namespace Samples.AspNet.VB.Controls

  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public Interface IZipCode

    Property ZipCode() As String

  End Interface

  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public Class ZipCodeWebPart
    Inherits WebPart
    Implements IZipCode
    Private zipCodeText As String = String.Empty
    Private input As TextBox
    Private send As Button

    Public Sub New()
    End Sub

    ' Make the implemented property personalizable to save 
    ' the Zip Code between browser sessions.
    <Personalizable()> _
    Public Property ZipCode() As String _
      Implements IZipCode.ZipCode

      Get
        Return zipCodeText
      End Get
      Set(ByVal value As String)
        zipCodeText = value
      End Set
    End Property

    ' This is the callback method that returns the provider.
    <ConnectionProvider("Zip Code Provider", "ZipCodeProvider")> _
    Public Function ProvideIZipCode() As IZipCode
      Return Me
    End Function


    Protected Overrides Sub CreateChildControls()
      Controls.Clear()
      input = New TextBox()
      Me.Controls.Add(input)
      send = New Button()
      send.Text = "Enter 5-digit Zip Code"
      AddHandler send.Click, AddressOf Me.submit_Click
      Me.Controls.Add(send)

    End Sub


    Private Sub submit_Click(ByVal sender As Object, _
      ByVal e As EventArgs)

      If input.Text <> String.Empty Then
        zipCodeText = Page.Server.HtmlEncode(input.Text)
        input.Text = String.Empty
      End If

    End Sub

  End Class

  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public Class WeatherWebPart
    Inherits WebPart
    Private _provider As IZipCode
    Private _zipSearch As String
    Private DisplayContent As Label

    ' This method is identified by the ConnectionConsumer 
    ' attribute, and is the mechanism for connecting with 
    ' the provider. 
    <ConnectionConsumer("Zip Code Consumer", "ZipCodeConsumer")> _
    Public Sub GetIZipCode(ByVal Provider As IZipCode)
      _provider = Provider
    End Sub


    Protected Overrides Sub OnPreRender(ByVal e As EventArgs)
      EnsureChildControls()

      If Not (Me._provider Is Nothing) Then
        _zipSearch = _provider.ZipCode.Trim()
                DisplayContent.Text = "My Zip Code is:  " + _zipSearch
      End If

    End Sub

    Protected Overrides Sub CreateChildControls()
      Controls.Clear()
      DisplayContent = New Label()
      Me.Controls.Add(DisplayContent)

    End Sub

  End Class

End Namespace

The third part of the code example is the Web page. Near the top are the Register directives for the user control and the custom WebPart controls. Because the example assumes dynamic compilation of the controls, the source code for the controls should be in an App_Code subfolder; the Register tag in the page references only an arbitrary tag prefix and the namespace of the controls. The custom WebPart controls (the provider and consumer) are declared within the Web page's <asp:webpartzone> element, inside a <zonetemplate> element.

The page provides three ways to form a connection between the custom controls. The first method is declarative. In the markup for the page, a <StaticConnections> element is declared, and within that is an <asp:WebPartConnections> element, with the various consumer and provider details of the connection specified as attributes. This is one way to create a connection, by declaring it directly in the Web page, specifically within the <asp:WebPartManager> element. Because of this static connection, a connection between the two custom controls is created immediately the first time the page loads.

A second method for forming a connection between the controls is provided by the <asp:connectionszone> element in the page. If a user switches a page into connect display mode at run time, and clicks a connect verb on one of the custom controls, the <asp:connectionszone> element automatically renders the UI for creating a connection.

The page also demonstrates a third way of creating a connection, which is to do it programmatically. In the Button1_Click method, the code creates a ProviderConnectionPoint object for the provider control, and retrieves its connection point details by calling the GetProviderConnectionPoints method. It carries out a similar task for the consumer control, calling the GetConsumerConnectionPoints method. Finally, it creates the new WebPartConnection object by calling the ConnectWebParts method on the WebPartManager control.

<%@ Page Language="C#" %>
<%@ Register TagPrefix="uc1" 
    TagName="DisplayModeMenuCS"
    Src="~/displaymodemenucs.ascx" %>
<%@ Register TagPrefix="aspSample" 
    Namespace="Samples.AspNet.CS.Controls" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  protected void Button1_Click(object sender, EventArgs e)
  {
    ProviderConnectionPoint provPoint = 
      mgr.GetProviderConnectionPoints(zip1)["ZipCodeProvider"];
    ConsumerConnectionPoint connPoint = 
      mgr.GetConsumerConnectionPoints(weather1)["ZipCodeConsumer"];
    WebPartConnection conn1 = mgr.ConnectWebParts(zip1, provPoint,
      weather1, connPoint);
  }

  protected void mgr_DisplayModeChanged(object sender, 
    WebPartDisplayModeEventArgs e)
  {
    if (mgr.DisplayMode == WebPartManager.ConnectDisplayMode)
      Button1.Visible = true;
    else
      Button1.Visible = false;
  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:WebPartManager ID="mgr" runat="server" 
    OnDisplayModeChanged="mgr_DisplayModeChanged">
        <StaticConnections>
          <asp:WebPartConnection ID="conn1"
            ConsumerConnectionPointID="ZipCodeConsumer"
            ConsumerID="weather1"
            ProviderConnectionPointID="ZipCodeProvider"
            ProviderID="zip1" />
        </StaticConnections>
      </asp:WebPartManager>
      <uc1:DisplayModeMenuCS ID="menu1" runat="server" />
      <asp:WebPartZone ID="WebPartZone1" runat="server">
        <ZoneTemplate>
          <aspSample:ZipCodeWebPart ID="zip1" runat="server"
            Title="Zip Code Provider" />
          <aspSample:WeatherWebPart ID="weather1" runat="server" 
            Title="Zip Code Consumer" />
        </ZoneTemplate>
      </asp:WebPartZone>
      <asp:ConnectionsZone ID="ConnectionsZone1" runat="server">
      </asp:ConnectionsZone>
      <asp:Button ID="Button1" runat="server" 
        Text="Connect WebPart Controls" 
        OnClick="Button1_Click" 
    Visible="false" />
    </div>
    </form>
</body>
</html>
<%@ Page Language="vb" %>
<%@ Register TagPrefix="uc1" 
    TagName="DisplayModeMenuVB"
    Src="~/displaymodemenuvb.ascx" %>
<%@ Register TagPrefix="aspSample" 
    Namespace="Samples.AspNet.VB.Controls" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  Protected Sub Button1_Click(ByVal sender As Object, _
    ByVal e As System.EventArgs)
    
    Dim provPoint As ProviderConnectionPoint = _
      mgr.GetProviderConnectionPoints(zip1)("ZipCodeProvider")
    Dim connPoint As ConsumerConnectionPoint = _
      mgr.GetConsumerConnectionPoints(weather1)("ZipCodeConsumer")
    mgr.ConnectWebParts(zip1, provPoint, weather1, connPoint)

  End Sub

  Protected Sub mgr_DisplayModeChanged (ByVal sender as Object, _
    ByVal e as WebPartDisplayModeEventArgs)

    If mgr.DisplayMode Is WebPartManager.ConnectDisplayMode Then
    Button1.Visible = True
    Else
    Button1.Visible = False
    End If

  End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:WebPartManager ID="mgr" runat="server" 
    OnDisplayModeChanged="mgr_DisplayModeChanged">
        <StaticConnections>
          <asp:WebPartConnection ID="conn1"
            ConsumerConnectionPointID="ZipCodeConsumer"
            ConsumerID="weather1"
            ProviderConnectionPointID="ZipCodeProvider"
            ProviderID="zip1" />
        </StaticConnections>
      </asp:WebPartManager>
      <uc1:DisplayModeMenuVB ID="menu1" runat="server" />
      <asp:WebPartZone ID="WebPartZone1" runat="server">
        <ZoneTemplate>
          <aspSample:ZipCodeWebPart ID="zip1" runat="server"
            Title="Zip Code Provider" />
          <aspSample:WeatherWebPart ID="weather1" runat="server" 
            Title="Zip Code Consumer" />
        </ZoneTemplate>
      </asp:WebPartZone>
      <asp:ConnectionsZone ID="ConnectionsZone1" runat="server">
      </asp:ConnectionsZone>
      <asp:Button ID="Button1" runat="server" 
        Text="Connect WebPart Controls" 
        OnClick="Button1_Click" 
    Visible="false" />
    </div>
    </form>
</body>
</html>

After you load the Web page in a browser, the first connection already exists because it is declared within the <StaticConnections> element. Enter some text in the ZIP Code Provider control, and it will be displayed in the consumer control. Next, disconnect the two controls. Using the Display Mode drop-down list control, change the page to connect display mode. Click the verbs menu (represented by a downward arrow in the title bar) for each of the WebPart controls, and notice that each has a Connect option. This is a connect verb, which appears in the verbs menu only when the page is in connect mode. Click the connect verb on one of the controls, and the connection UI provided by the ConnectionsZone control appears. Click the Disconnect button to end the static connection between the controls. Use the Display Mode control to return the page to browse mode. Try to enter some new text in the provider again, and note that because the controls are disconnected, the text fails to update in the consumer control.

Next, use the same method as above to switch the page into connect display mode again. Click a connect verb on one of the controls. Click the Create a Connection link, and use the UI provided by the ConnectionsZone control to create a connection between the controls. This is the second method for creating a connection. Note that as soon as the connection is formed, the last string you entered in the provider control (that failed to appear because the controls were disconnected) suddenly appears in the consumer, because the connection has been recreated. Click the Disconnect button to end the current connection that you just created. Return the page to browse mode. Enter some new text in the provider to demonstrate that the text is not updated, and that the controls are again disconnected.

Return the page to connect display mode. Instead of clicking a connect verb, click the Connect WebPart Controls button, which illustrates the third method of forming a connection. This approach connects the controls programmatically in one simple step without having to use the ConnectionsZone control. Note that as the connection is created, the last string you entered in the provider suddenly appears in the consumer control.

Remarks

In the Web Parts control set, a connection is a link or association between two WebPart (or other server or user) controls that enables them to share data. This ability to share data allows connected controls to be used in ways that exceed the functionality offered by the isolated controls. For example, if one control provides postal code data, and another control can read that data and provide local weather information based on the postal code, then the connected capability of the two controls provides more value to users. To extend this example, other controls could be created that also display information based on a postal code, such as a control with links to local news, and all these controls that can work with postal code data could share data with the single control that provides a postal code. End users of Web Parts applications can create and manage connections between all such compatible controls directly from a Web browser, using the standard connections user interface (UI) provided by the ConnectionsZone control, or using a custom UI provided by a developer.

This WebPartConnection class overview is a general statement of the basic details for creating a connection. For more on specific components and requirements involved in creating connections, see Web Parts Connections Overview, or see the reference classes and code examples mentioned in the following discussion. There are several fundamental aspects of a Web Parts connection:

  • Two WebPart controls. Every Web Parts connection consists of two controls. It is possible for a control to participate in more than one connection simultaneously, but every single connection consists of exactly two controls. The controls can derive directly from the WebPart base class, or they can be other server controls, including ASP.NET controls, custom server controls, and user controls. Controls that do not derive from the WebPart class, if placed in a WebPartZoneBase zone, are automatically wrapped with a GenericWebPart object at run time, which enables them to inherit from the WebPart class and function as run-time WebPart controls.

  • Controls residing in WebPartZoneBase zones. Both WebPart controls and any other type of server control must reside in a WebPartZoneBase zone to be able to participate in Web Parts connections (and most other Web Parts features).

  • Consumers and providers. In every Web Parts connection there are two controls: a provider of data and a consumer of data. The provider furnishes data to the consumer through a specified callback method that returns data in the form of an interface. (For an example of how to create and specify the callback method, see the Example section of this topic.) This callback method is known as a provider connection point. The details of this connection point (its "friendly" name, an ID, and the type of the returned interface) are contained in a ProviderConnectionPoint object associated with the provider control. The consumer receives the data through a specified method that can accept an instance of the interface. This method is known as a consumer connection point, and the details of the connection point (name, ID, and type of interface) are contained in a ConsumerConnectionPoint object associated with the consumer control.

  • Compatible controls or a valid transformer. For a connection to work, the consumer and provider must either be compatible (meaning that their specified connection point methods can work with the same type of interface), or there must be a WebPartTransformer object capable of translating the type offered by the provider into a type understood by the consumer.

  • A WebPartConnection object. For a connection to exist, there must be an instance of the WebPartConnection class that contains references to the provider and consumer controls, along with the details of their connection points. If the provider and consumer are incompatible and instead use a WebPartTransformer object to connect, the connection references the transformer.

  • A means of establishing the connection. After compatible consumer and provider controls have been properly designed with connection point methods and placed in a zone, and a WebPartConnection object is available, the last basic step necessary is to initiate the connection. One way this can happen is for users to create the connection through the UI. If you place an <asp:connectionszone> element on the page, and the other required components for a connection are in place, at run time a user can switch the page into connect display mode, click a connect verb on the verbs menu of either the provider or consumer, and a connection UI (based on the ConnectionsZone control) will appear. Through this UI, the user can initiate the connection. Another way to initiate the connection is to do it programmatically. In either case, whether through the UI or programmatically, the underlying method that initiates the connection is the same. The application calls the ConnectWebParts method (or the ConnectWebParts method if using a transformer) on the WebPartManager control, passing to it the provider, the consumer, and their respective connection point objects, and the method returns a WebPartConnection object.

The WebPartConnection class defines an object that encapsulates the essential details of a connection between two WebPart controls. The class consists almost entirely of properties related to the details of a particular connection. Several properties concern the consumer control in a connection. The Consumer property references the consumer control itself, and the ConsumerID property references the consumer's ID. The ConsumerConnectionPoint object, which contains the details of the consumer's connection point, is referenced by the consumer's ConsumerConnectionPoint property. The ConsumerConnectionPointID property references the ID of the ConsumerConnectionPoint object. All these consumer-related connection properties must have a value assigned to them to create a connection.

The WebPartConnection class also has several properties that relate to the provider control in a connection, and these correspond to the properties for a consumer. The Provider property references the provider control itself, while the ProviderID property references its ID. The ProviderConnectionPoint property references the ProviderConnectionPoint object, and the ProviderConnectionPointID property references the ID of the provider's connection point.

Several properties concern the state of the connection. The IsActive property indicates whether the connection is active (currently exchanging data) or inactive (still connected but not actively sharing data). The IsShared property indicates whether the connection is a shared (available to all users of a page) or a user-specific connection, and the IsStatic property indicates whether the control is static (declared in the page markup and thus permanent) or dynamic (created programmatically, meaning that it can be deleted).

Constructors

WebPartConnection()

Initializes a new instance of the WebPartConnection class.

Properties

Consumer

Gets a WebPart object that is acting as the consumer control in a connection.

ConsumerConnectionPoint

Gets the object that serves as a connection point for a control that is acting as a consumer in a connection.

ConsumerConnectionPointID

Gets or sets the property value on a connection that references the ID of the object serving as the consumer connection point for that connection.

ConsumerID

Gets or sets the property value on a connection that references the ID of the WebPart control acting as a consumer for that connection.

ID

Gets or sets the ID of a WebPartConnection object.

IsActive

Gets a value that indicates whether a WebPartConnection object is currently established and able to exchange data between its provider and consumer controls.

IsShared

Gets a value that indicates whether a WebPartConnection object is visible to all users or only to the current user.

IsStatic

Gets a value that indicates whether a WebPartConnection object is declared in the markup of a Web page, or created programmatically.

Provider

Gets a WebPart control that acts as the provider in a Web Parts connection.

ProviderConnectionPoint

Gets the object that serves as a connection point for a WebPart control acting as a provider for a connection.

ProviderConnectionPointID

Gets or sets the property value on a connection that references the ID of the object serving as the provider connection point for that connection.

ProviderID

Gets or sets the property value on a connection that references the ID of the WebPart control acting as a provider for that connection.

Transformer

Gets a WebPartTransformer object that is used to transform data between two otherwise incompatible connection points in a Web Parts connection.

Transformers

Gets a collection of WebPartTransformer objects used internally by the Web Parts control set.

Methods

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
ToString()

Overrides the inherited ToString() method and returns a short type name for the connection object.

Applies to

See also