WebPartManager.AddWebPart(WebPart, WebPartZoneBase, Int32) Método

Definição

Fornece o método programático padrão para adicionar controles WebPart a uma página da Web.Provides the standard programmatic method for adding WebPart controls to a Web page.

public:
 System::Web::UI::WebControls::WebParts::WebPart ^ AddWebPart(System::Web::UI::WebControls::WebParts::WebPart ^ webPart, System::Web::UI::WebControls::WebParts::WebPartZoneBase ^ zone, int zoneIndex);
public System.Web.UI.WebControls.WebParts.WebPart AddWebPart (System.Web.UI.WebControls.WebParts.WebPart webPart, System.Web.UI.WebControls.WebParts.WebPartZoneBase zone, int zoneIndex);
member this.AddWebPart : System.Web.UI.WebControls.WebParts.WebPart * System.Web.UI.WebControls.WebParts.WebPartZoneBase * int -> System.Web.UI.WebControls.WebParts.WebPart
Public Function AddWebPart (webPart As WebPart, zone As WebPartZoneBase, zoneIndex As Integer) As WebPart

Parâmetros

webPart
WebPart

O WebPart (ou o controle de servidor ou usuário) a ser adicionado a uma página da Web ou aberto em uma página.The WebPart (or server or user control) to be added to a Web page or opened on a page.

zone
WebPartZoneBase

O WebPartZoneBase ao qual o webPart está sendo adicionado.The WebPartZoneBase that webPart is being added to.

zoneIndex
Int32

Um inteiro que representa a posição ordinal que o webPart ocupa no zone, em relação a outros controles no zone.An integer that represents the ordinal position that webPart occupies in zone, relative to other controls in zone.

Retornos

WebPart

Um controle WebPart que foi adicionado à página.A WebPart control that was added to the page.

Exceções

webPart é null.webPart is null.

- ou --or- zone é null.zone is null.

zone não está registrado na coleção de zonas do controle WebPartManager.zone is not registered in the WebPartManager control's collection of zones.

- ou --or- webPart já está no zone.webPart is already in zone.

O valor do zoneIndex é menor que zero.The value of zoneIndex is less than zero.

Exemplos

O exemplo de código a seguir demonstra o uso do AddWebPart método para adicionar um controle de servidor programaticamente a uma página.The following code example demonstrates use of the AddWebPart method to add a server control programmatically to a page. A marcação de página contém um <asp:webpartzone> elemento vazio e um <asp:webpartmanager> elemento.The page markup contains an empty <asp:webpartzone> element, and an <asp:webpartmanager> element. Na primeira vez que o botão adicionar calendário é clicado, o código no manipulador de eventos cria um Calendar controle e o adiciona a uma zona como um GenericWebPart objeto, chamando o AddWebPart método.The first time the Add Calendar button is clicked, the code in the event handler creates a Calendar control, and adds it to a zone as a GenericWebPart object, calling the AddWebPart method.

<%@ Page Language="C#" %>

<!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 Button2_Click(object sender, EventArgs e)
  {
    WebPartManager mgr = WebPartManager1;
    Calendar cal = new Calendar();
    cal.ID = "cal1";
    GenericWebPart calWebPart = mgr.CreateWebPart(cal);
    mgr.AddWebPart(calWebPart, WebPartZone1, 1);
  }

  protected void Button1_Click(object sender, EventArgs e)
  {
    if (WebPartZone1.WebParts.Count > 1)
    {
      WebPart cal = WebPartZone1.WebParts[1];
      if (cal.Controls[0].GetType().Name == "Calendar" 
        && cal != null)
        WebPartManager1.DeleteWebPart(cal);
    }

  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Adding a Server Control</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:WebPartManager ID="WebPartManager1" 
        runat="server" />
      <asp:WebPartZone ID="WebPartZone1" runat="server">
        <ZoneTemplate>
          <asp:BulletedList  
            DisplayMode="HyperLink" 
            ID="BulletedList1" 
            runat="server"
            Title="My Links">
            <asp:ListItem Value="http://www.microsoft.com">
            Microsoft
            </asp:ListItem>
            <asp:ListItem Value="http://www.msn.com">
            MSN
            </asp:ListItem>
            <asp:ListItem Value="http://www.contoso.com">
            Contoso Corp.
            </asp:ListItem>
          </asp:BulletedList>
        </ZoneTemplate>
      </asp:WebPartZone>
      <asp:Button ID="Button1" runat="server" 
        Text="Delete Calendar" 
        OnClick="Button1_Click" />
      <asp:Button ID="Button2" runat="server" 
        Text="Add Calendar" 
        OnClick="Button2_Click" />
    </div>
    </form>
</body>
</html>
<%@ Page Language="vb" %>

<!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 Button2_Click(ByVal sender As Object, _
    ByVal e As System.EventArgs)
    Dim mgr As WebPartManager = WebPartManager1
    Dim cal As New Calendar()
    cal.ID = "cal1"
    Dim calWebPart As GenericWebPart = mgr.CreateWebPart(cal)
    mgr.AddWebPart(calWebPart, WebPartZone1, 1)
  End Sub

  Protected Sub Button1_Click(ByVal sender As Object, _
    ByVal e As System.EventArgs)

    If WebPartZone1.WebParts.Count > 1 Then
      Dim cal As WebPart = WebPartZone1.WebParts(1)
      If cal.Controls(0).GetType().Name = "Calendar" AndAlso _
        cal IsNot Nothing Then
        WebPartManager1.DeleteWebPart(cal)
      End If
    End If
  End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Adding a Server Control</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:WebPartManager ID="WebPartManager1" 
        runat="server" />
      <asp:WebPartZone ID="WebPartZone1" runat="server">
        <ZoneTemplate>
          <asp:BulletedList  
            DisplayMode="HyperLink" 
            ID="BulletedList1" 
            runat="server"
            Title="My Links">
            <asp:ListItem Value="http://www.microsoft.com">
            Microsoft
            </asp:ListItem>
            <asp:ListItem Value="http://www.msn.com">
            MSN
            </asp:ListItem>
            <asp:ListItem Value="http://www.contoso.com">
            Contoso Corp.
            </asp:ListItem>
          </asp:BulletedList>
        </ZoneTemplate>
      </asp:WebPartZone>
      <asp:Button ID="Button1" runat="server" 
        Text="Delete Calendar" 
        OnClick="Button1_Click" />
      <asp:Button ID="Button2" runat="server" 
        Text="Add Calendar" 
        OnClick="Button2_Click" />
    </div>
    </form>
</body>
</html>

Comentários

O AddWebPart método é usado para adicionar novos controles dinâmicos WebPart a uma página e para reabrir controles estáticos ou dinâmicos que foram fechados anteriormente em uma página.The AddWebPart method is used both to add new dynamic WebPart controls to a page, and to reopen static or dynamic controls that have previously been closed on a page. Quando o método é chamado para adicionar um novo controle, ele realmente cria uma cópia do controle referenciado no webPart parâmetro.When the method is called to add a new control, it actually creates a copy of the control referenced in the webPart parameter. Uma nova ID é gerada para a cópia do controle, de modo que os desenvolvedores devem referenciar o WebPart controle retornado do método para obter o novo valor de ID.A new ID is generated for the copy of the control, so developers should reference the WebPart control returned from the method to get the new ID value. Quando o método é chamado para reabrir um controle anteriormente fechado, ele retorna uma referência direta ao controle referenciado pelo webPart parâmetro.When the method is called to reopen a previously closed control, it returns a direct reference to the control referenced by the webPart parameter.

Importante

Você sempre deve usar o AddWebPart método, em vez do Add método da coleção de controles referenciada pela WebPartManager.Controls propriedade, para adicionar WebPart controles programaticamente à página, porque o uso do Add método gera uma exceção.You should always use the AddWebPart method, rather than the Add method of the collection of controls referenced by the WebPartManager.Controls property, to add WebPart controls programmatically to the page, because using the Add method throws an exception. Para adicionar um controle que não é um WebPart controle (em outras palavras, um controle de servidor que será encapsulado com um GenericWebPart controle em tempo de execução), primeiro você deve chamar o CreateWebPart método para criar o controle e, em seguida, chamar o AddWebPart método para adicionar o controle.To add a control that is not a WebPart control (in other words, a server control that will be wrapped with a GenericWebPart control at run time), you should first call the CreateWebPart method to create the control, and then call the AddWebPart method to add the control. Para ver uma demonstração dessa abordagem, consulte a seção de exemplo.For a demonstration of this approach, see the Example section.

Aplica-se a

Confira também