WebPartManager.DisconnectWebPart(WebPart) 方法

定义

移除要关闭或要从其所参与的连接中删除的 WebPart 或服务器控件。Removes a WebPart or server control that is being closed or deleted from any connections it is participating in.

protected:
 virtual void DisconnectWebPart(System::Web::UI::WebControls::WebParts::WebPart ^ webPart);
protected virtual void DisconnectWebPart (System.Web.UI.WebControls.WebParts.WebPart webPart);
abstract member DisconnectWebPart : System.Web.UI.WebControls.WebParts.WebPart -> unit
override this.DisconnectWebPart : System.Web.UI.WebControls.WebParts.WebPart -> unit
Protected Overridable Sub DisconnectWebPart (webPart As WebPart)

参数

webPart
WebPart

要断开连接的 WebPart 控件。A WebPart control that is to be disconnected.

示例

下面的代码示例演示如何使用 DisconnectWebPart 方法。The following code example demonstrates how to use the DisconnectWebPart method. 通过使用两个自定义 WebPart 控件,可通过单击按钮在控件之间创建连接,而使用另一个按钮可以断开控件的连接。Using two custom WebPart controls, the Web page enables you to create a connection between the controls by clicking a button, while another button enables you to disconnect the controls. 如果在页处于浏览模式并且控件已连接时关闭其中一个控件,则该方法的重写会 DisconnectWebPart 断开关闭的控件的连接,结束连接,并显示一条消息。If you close one of the controls while the page is in browse mode and the controls are connected, an override of the DisconnectWebPart method disconnects the closed control, ends the connection, and displays a message.

此代码示例包含四个部分:The code example has four parts:

  • 用于更改显示模式的用户控件。A user control for changing display modes.

  • 包含自定义控件的源文件 WebPartA source file containing custom WebPart controls.

  • 用于承载控件的网页。A Web page to host the controls.

  • 说明如何在浏览器中工作。An explanation of how the example works in a browser.

此代码示例的第一部分是用户控件,用于更改显示模式。The first part of the code example is the user control for changing display modes. 你可以从类概述的 "示例" 部分获取用户控件的源代码 WebPartManagerYou can obtain the source code for the user control from the Example section of the WebPartManager class overview. 有关显示模式和用户控件工作方式的详细信息,请参阅 演练:更改 Web 部件页上的显示模式For more information about display modes and how the user control works, see Walkthrough: Changing Display Modes on a Web Parts Page.

第二部分是包含两个要连接的自定义控件的源代码的文件 WebPart ,以及一个自定义 WebPartManager 控件。The second part is the file containing the source code for the two custom WebPart controls that will be connected, and a custom WebPartManager control. 要使代码示例运行,必须编译此源代码。For the code example to run, you must compile this source code. 可以显式编译该程序集,并将生成的程序集放在网站的 Bin 文件夹或全局程序集缓存中。You can compile it explicitly and put the resulting assembly in your Web site's Bin folder or the global assembly cache. 或者,您可以将源代码放在站点的 App_Code 文件夹中,它将在运行时动态编译。Alternatively, you can put the source code in your site's App_Code folder, where it will be dynamically compiled at run time. 此示例使用动态编译,因此在网页 Register 顶部声明了引用这些组件的指令。This example uses dynamic compilation, so the Register directive that references these components in the Web page is declared accordingly at the top of the Web page. 有关演示如何编译选项的演练,请参阅 演练:开发和使用自定义 Web 服务器控件For a walkthrough that demonstrates compiling options, see Walkthrough: Developing and Using a Custom Web Server Control.

在源代码中,请注意重写方法的继承的控件 MyWebPartManager DisconnectWebPartIn the source code, notice the inherited control MyWebPartManager that overrides the DisconnectWebPart method. 此方法检查页中的每个连接,以查看关闭的控件是否参与连接,如果是,则调用 DisconnectWebParts 方法以终止连接。This method checks each connection in a page to see whether the control being closed participates in the connection and, if so, calls the DisconnectWebParts method to end the connection. 这与控件中的方法的基实现完全相同 WebPartManagerThis is identical to the base implementation of the method in the WebPartManager control. 然后,重写的方法通过将消息写入页面来自定义基实现。The overridden method then customizes the base implementation by writing a message to the page.

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", "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", "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", "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", "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. 请注意,在顶部附近,它包含 Register 用控件注册用户控件和动态编译的程序集的指令 WebPartNotice that near the top, it contains Register directives to register the user control, and the dynamically compiled assembly with the WebPart controls. 此页具有两种主要方法。The page has two primary methods. Button1_Click方法在控件之间创建连接,而 Button2_Click 方法断开控件的连接。The Button1_Click method creates a connection between the controls, while the Button2_Click method disconnects the controls.

<%@ 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 Button2_Click(object sender, EventArgs e)
  {
    if (mgr.Connections.Count >= 1 && mgr.Connections[0] != null)
      mgr.DisconnectWebParts(mgr.Connections[0]);
  }
  

</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">
      </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" />
      <asp:Button ID="Button2" runat="server" 
        Text="Disconnect WebPart Controls" 
        OnClick="Button2_Click" />
    </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 mgr As WebPartManager = _
      WebPartManager.GetCurrentWebPartManager(Page)
    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 Button2_Click(ByVal sender as Object, _
    ByVal e as System.EventArgs)
    
    If mgr.Connections.Count >= 1 AndAlso _
      mgr.Connections(0) IsNot Nothing Then
      mgr.DisconnectWebParts(mgr.Connections(0))
    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">
      </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" />
      <asp:Button ID="Button2" runat="server" 
        Text="Disconnect WebPart Controls" 
        OnClick="Button2_Click" />
    </div>
    </form>
</body>
</html>

加载页面后,单击 " 连接 " 按钮以连接控件。After you load the page, click the Connect button to connect the controls. 然后单击其中一个控件中的谓词菜单 (控件标题中的向下箭头) ,然后在谓词菜单中选择 " 关闭 "。Then click the verbs menu in one of the controls (the downward arrow in the header of the control), and select Close from the verbs menu. 尝试关闭控件时,将调用重写的方法,连接将结束,并且消息将写入页面。When you try to close the control, the overridden method is called, the connection is ended, and the message is written to the page. 如果要重置页面以还原关闭的控件并尝试其他选项,请单击 " 重置用户状态 " 链接以删除个性化设置数据并还原页面的原始状态。If you want to reset the page to restore the closed control and experiment with other options, click the Reset User State link to remove personalization data and restore the page's original state.

注解

DisconnectWebPart当控件在页上关闭或从页中删除时,该方法由 Web 部件控件集进行内部调用。The DisconnectWebPart method is called internally by the Web Parts control set when a control is either closed on a page or deleted from a page. 在这种情况下,将调用方法,以将控件从任何连接(其中包含为使用者或提供者)中删除。In such a scenario, the method is called to remove the control from any connections where it is involved as a consumer or provider. 如果从任何连接中删除该控件,则此方法还会调用 DisconnectWebParts 方法以结束涉及的任何连接 webPartIf the control is removed from any connection, this method also calls the DisconnectWebParts method to end any connections in which webPart was involved.

DisconnectWebPart调用方法时,它会引发 WebPartsDisconnecting 事件。When the DisconnectWebPart method is called, it raises the WebPartsDisconnecting event. 通常可以取消此事件,但在两种情况下,不能取消此事件。Normally this event can be cancelled, but in two cases it cannot be cancelled. 当调用方法时,会在对页面的请求期间发生一种情况 ActivateConnectionsOne case occurs during requests to the page, when the ActivateConnections method is called. 如果现有连接之间存在冲突,则 DisconnectWebPart 将调用方法关闭其中一个冲突的连接,在此实例中, WebPartsDisconnecting 无法取消该事件,因为必须解决冲突。If there is a conflict among existing connections, the DisconnectWebPart method will be invoked to close one of the conflicting connections, and in this instance the WebPartsDisconnecting event cannot be cancelled, because the conflict must be resolved.

WebPart 当前连接的或服务器控件关闭或删除时,会发生另一种情况。The other case occurs when a WebPart or server control that is currently connected is either closed or deleted. 在这种情况下,由于正在从页面中删除控件,因此还需要终止其连接,因此,设计不能取消 WebPartsDisconnecting 事件以中断结束连接的过程。In this case, because of the control is being removed from the page, its connection needs to be terminated as well, therefore by design it is not possible to cancel the WebPartsDisconnecting event to interrupt the process of ending a connection. 有关详细信息,请参阅 WebPartsDisconnecting 事件。For more information, see the WebPartsDisconnecting event.

适用于

另请参阅