WebPartManager.DisconnectWebPart(WebPart) Metodo

Definizione

Rimuove un controllo WebPart o un controllo server in fase di chiusura o di eliminazione dalle connessioni a cui prende parte.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

Parametri

webPart
WebPart

Controllo WebPart da disconnettere.A WebPart control that is to be disconnected.

Esempi

Nell'esempio di codice riportato di seguito viene illustrato come utilizzare il metodo DisconnectWebPart.The following code example demonstrates how to use the DisconnectWebPart method. Utilizzando due controlli WebPart personalizzati, la pagina Web consente di creare una connessione tra i controlli facendo clic su un pulsante, mentre un altro pulsante consente di disconnettere i controlli.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. Se si chiude uno dei controlli mentre la pagina è in modalità browse e i controlli sono connessi, un override del DisconnectWebPart metodo disconnette il controllo chiuso, termina la connessione e visualizza un messaggio.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.

L'esempio di codice è costituito da quattro parti:The code example has four parts:

  • Controllo utente per la modifica delle modalità di visualizzazione.A user control for changing display modes.

  • File di origine contenente controlli WebPart personalizzati.A source file containing custom WebPart controls.

  • Pagina Web per ospitare i controlli.A Web page to host the controls.

  • Spiegazione del funzionamento dell'esempio in un browser.An explanation of how the example works in a browser.

La prima parte dell'esempio di codice è il controllo utente per la modifica delle modalità di visualizzazione.The first part of the code example is the user control for changing display modes. È possibile ottenere il codice sorgente per il controllo utente dalla sezione esempio della panoramica della WebPartManager classe.You can obtain the source code for the user control from the Example section of the WebPartManager class overview. Per ulteriori informazioni sulle modalità di visualizzazione e sul funzionamento del controllo utente, vedere Procedura dettagliata: Modifica delle modalità di visualizzazione in unapagina Web part.For more information about display modes and how the user control works, see Walkthrough: Changing Display Modes on a Web Parts Page.

La seconda parte è il file contenente il codice sorgente per i due controlli WebPart personalizzati che saranno connessi e un controllo personalizzato. WebPartManagerThe second part is the file containing the source code for the two custom WebPart controls that will be connected, and a custom WebPartManager control. Per eseguire l'esempio di codice, è necessario compilare questo codice sorgente.For the code example to run, you must compile this source code. È possibile compilarlo in modo esplicito e inserire l'assembly risultante nella cartella bin del sito Web o nel Global Assembly Cache.You can compile it explicitly and put the resulting assembly in your Web site's Bin folder or the global assembly cache. In alternativa, è possibile inserire il codice sorgente nella cartella App_Code del sito, in cui verrà compilato dinamicamente in fase di esecuzione.Alternatively, you can put the source code in your site's App_Code folder, where it will be dynamically compiled at run time. In questo esempio viene utilizzata la compilazione dinamica Register , pertanto la direttiva che fa riferimento a questi componenti nella pagina Web viene dichiarata di conseguenza nella parte superiore della pagina Web.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. Per una procedura dettagliata che illustra la compilazione di opzioni , vedere Procedura dettagliata: Sviluppo e utilizzo di un controlloserver Web personalizzato.For a walkthrough that demonstrates compiling options, see Walkthrough: Developing and Using a Custom Web Server Control.

Nel codice sorgente si noti il controllo MyWebPartManager ereditato che esegue l'override del DisconnectWebPart metodo.In the source code, notice the inherited control MyWebPartManager that overrides the DisconnectWebPart method. Questo metodo controlla ogni connessione in una pagina per verificare se il controllo da chiudere partecipa alla connessione e, in caso affermativo, chiama il DisconnectWebParts metodo per terminare la connessione.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. Questo è identico all'implementazione di base del metodo nel WebPartManager controllo.This is identical to the base implementation of the method in the WebPartManager control. Il metodo sottoposto a override consente quindi di personalizzare l'implementazione di base scrivendo un messaggio nella pagina.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

La terza parte dell'esempio di codice è la pagina Web.The third part of the code example is the Web page. Si noti che nella parte superiore sono contenute Register le direttive per registrare il controllo utente e l'assembly compilato dinamicamente con i WebPart controlli.Notice that near the top, it contains Register directives to register the user control, and the dynamically compiled assembly with the WebPart controls. La pagina dispone di due metodi principali.The page has two primary methods. Il Button1_Click metodo crea una connessione tra i controlli, mentre il Button2_Click metodo disconnette i controlli.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>

Una volta caricata la pagina, fare clic sul pulsante Connetti per connettere i controlli.After you load the page, click the Connect button to connect the controls. Fare quindi clic sul menu dei verbi in uno dei controlli (la freccia verso il basso nell'intestazione del controllo) e scegliere Chiudi dal menu dei verbi.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. Quando si tenta di chiudere il controllo, viene chiamato il metodo sottoposto a override, la connessione viene terminata e il messaggio viene scritto nella pagina.When you try to close the control, the overridden method is called, the connection is ended, and the message is written to the page. Se si vuole reimpostare la pagina per ripristinare il controllo chiuso e sperimentare altre opzioni, fare clic sul collegamento Reimposta stato utente per rimuovere i dati di personalizzazione e ripristinare lo stato originale della pagina.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.

Commenti

Il DisconnectWebPart metodo viene chiamato internamente dal set di controlli di Web part quando un controllo viene chiuso in una pagina o eliminato da una pagina.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 uno scenario di questo tipo, viene chiamato il metodo per rimuovere il controllo da qualsiasi connessione in cui è richiesto come consumer o provider.In such a scenario, the method is called to remove the control from any connections where it is involved as a consumer or provider. Se il controllo viene rimosso da qualsiasi connessione, questo metodo chiama anche il DisconnectWebParts metodo per terminare tutte le connessioni in webPart cui è stato richiesto.If the control is removed from any connection, this method also calls the DisconnectWebParts method to end any connections in which webPart was involved.

Quando viene DisconnectWebPart chiamato il metodo, viene generato l' WebPartsDisconnecting evento.When the DisconnectWebPart method is called, it raises the WebPartsDisconnecting event. In genere, questo evento può essere annullato, ma in due casi non può essere annullato.Normally this event can be cancelled, but in two cases it cannot be cancelled. Si verifica un caso durante le richieste alla pagina, quando ActivateConnections viene chiamato il metodo.One case occurs during requests to the page, when the ActivateConnections method is called. Se si verifica un conflitto tra le connessioni esistenti, DisconnectWebPart il metodo verrà richiamato per chiudere una delle connessioni in conflitto e in questo caso l' WebPartsDisconnecting evento non può essere annullato, perché il conflitto deve essere risolto.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.

L'altro caso si verifica quando WebPart un controllo o un controllo server attualmente connesso viene chiuso o eliminato.The other case occurs when a WebPart or server control that is currently connected is either closed or deleted. In questo caso, a causa della rimozione del controllo dalla pagina, anche la connessione deve essere terminata, quindi, per impostazione predefinita, non è possibile annullare l' WebPartsDisconnecting evento per interrompere il processo di chiusura di una connessione.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. Per altre informazioni, vedere l'evento WebPartsDisconnecting.For more information, see the WebPartsDisconnecting event.

Si applica a

Vedi anche