使用ascx动态创建webpart

Control       oCon2       =       Page.LoadControl( "W3.ascx ");      
oCon2.ID       =       "ABC ";       
  WebPart       oPart       =       WebPartManager1.CreateWebPart(oCon2);       
   WebPartManager1.AddWebPart(oPart,       WebPartZone1,       0);

 

+++

在用编程方法加载用户定义的控件时,应注意到此时的控件还不能成为webpart控件,必须先用GenericWebPart 控件为不是 WebPart 控件的服务器控件提供运行时包装,以使任何 ASP.NET 控件、自定义控件或用户控件都可参与 Web 部件应用程序,然后再用CreateWebpart方法创建Web 部件,最后在用AddWebpart方法加到webpart区域。请看下面实例。

<%@ Page Language="vb" %>

<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 >
<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>

 

替换 xxxx.cs 文件中的RenderWebPart()方法。代码如下:

protected   override   void  RenderWebPart(HtmlTextWriter output)
{
    
this.EnsureChildControls();
    _innerWebControl.RenderControl(output);
}


private  System.Web.UI.Control _innerWebControl;

protected   override   void  CreateChildControls()
{
    _innerWebControl
=this.Page.LoadControl("/bin/WebUserControlTest.ascx");
    
this.Controls.Add(_innerWebControl);
    
base.CreateChildControls ();
}


其中 LoadControl("/bin/WebUserControlTest.ascx") 就是要加载的 *.ascx 文件名了。

你可能感兴趣的:(part)