Adicionando um Web User Control em um Webform dinamicamente

Postado por Daniel Garcia às 16:23 QUINTA-FEIRA, 9 DE JULHO DE 2009

Neste post mostratei com é simples adicionar um User Control dinamicamente em um Webform.

Veja o código da página a seguir:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
      <title></title>
</
head>
<
body>
      <form id="form1" runat="server">
      <div>
            <asp:Label ID="lblCabecalho" runat="server" Text="Label"></asp:Label>
            <asp:Label ID="lblRodape" runat="server" Text="Label"></asp:Label>
      </div>
      </form>
</
body>
</
html>

Para adicionar um User Control entre os labels "lblCabecalho" e "lblRodape" seguiremos os seguintes passos:

1 - Adicione um PlaceHolder entre os labels "lblCabecalho" e "lblRodape". O código ficará da seguinte forma:

...

<asp:Label ID="lblCabecalho" runat="server" Text="Label"></asp:Label>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:Label ID="lblRodape" runat="server" Text="Label"></asp:Label>

...

2 - Use o método LoadControl para passando o nome do UserControl para carregá-lo. E adicione-o ao PlaceHolder.

protected void Page_Load(object sender, EventArgs e)
{
     Control ctrl = LoadControl("UserCtrl.ascx");

     PlaceHolder1.Controls.Add(ctrl);
}

Espero que tenham gostado!

5.0 ponto(s). Avaliado por 1 pessoas

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

ASP.NET | C#

Comentários

Comentar


(Vai mostrar seu Gravatar)  

  Country flag

biuquote
  • Comentário
  • Pré-visualização
Loading



Sobre o Autor

Daniel Garcia - MCP, MCTS, MCPD
Meu nome é Daniel Garcia, venho atuando no mercado de tecnologia há mais de uma década. Durante esse tempo tive a oportunidade de trabalhar com diversas tecnologias, principalmente Microsoft. Conquistei os títulos: MCP, MCTS, MCDP e MCT. Desde então, venho contribuindo com toda a Comunidade, divulgando meu conhecimento das tecnologias Microsoft.