2012-07-10 80 views
1

我有一個用戶控件可編程地包含多次第二個用戶控件,但最終結果是根本沒有爲控件生成任何HTML。以編程方式嵌套ASP.NET用戶控件

Default.aspx的

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="TestApplication._Default" %> 
<%@ Register TagName="Ten" TagPrefix="me" Src="~/Ten.ascx" %> 

<html> 
<head runat="server"></head> 
<body> 
    <form id="form1" runat="server"> 
     <me:Ten ID="thisTen" runat="server" /> 
    </form> 
</body> 
</html> 

Ten.ascx

<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="Ten.ascx.vb" Inherits="TestApplication.Ten" %> 

<asp:Panel ID="List" runat="server"></asp:Panel> 

Ten.ascx.vb

Public Class Ten 
    Inherits System.Web.UI.UserControl 
    Protected Sub Page_Init() Handles Me.Init 
     For I As Integer = 0 To 11 
      List.Controls.Add(New One(I.ToString)) 
     Next 
    End Sub 
End Class 

One.ascx

<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="One.ascx.vb" Inherits="TestApplication.One" %> 

<asp:Button ID="OneButton" Text="Press ME!" runat="server" /> 

One.ascx.vb

Public Class One 
    Inherits System.Web.UI.UserControl 
    Private _number As String 
    Sub New(ByVal number As String) 
     _number = number 
    End Sub 
    Protected Sub OneButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles OneButton.Click 
     Dim script As String = "<script type=""text/javascript"">" + 
           "alert('Button " + _number + "');" + 
           "</script>" 
     ScriptManager.RegisterStartupScript(Me, Me.GetType(), "ServerControlScript", script, True) 
    End Sub 
End Class 

編輯:

使用負載控制(Ten.aspx)

Dim p() As String = {I.ToString} 
Dim o As One = Me.LoadControl(New One("").GetType, p) 
List.Controls.Add(o) 

編輯2:

Dim o As One = Me.LoadControl("~/One.ascx") 
o._number = I.ToString 
List.Controls.Add(o) 

回答

1

我不會不會執行此操作在OnInit事件中進行操作,但這可能與您的問題相關,也可能不相關。相反,我會在OnLoad事件中加載控件。

但是,使用new關鍵字通常不會如何加載用戶控件。很抱歉,但我只知道C#不知道確切的翻譯:

在C#:

One one = (One)this.LoadControl("~/Controls/One.ascx"); 

這是否期待權在VB.NET?

Dim one As One = Me.LoadControl("~/Controls/One.ascx") 

您可能必須刪除構造函數,並在加載控件後設置屬性。

+0

是的,除了構造函數有一個參數外,這是可行的。這會導致HttpCompileException。我可以通過傳入數組中的參數來解決這個問題。但是,這並沒有解決問題,仍然沒有生成HTML。 – papodaca 2012-07-10 05:21:29

+0

好的,所以確實這樣做,看看我改變了什麼編輯... – papodaca 2012-07-10 05:25:42

+0

@papodaca - 尼斯... – 2012-07-10 11:26:47

相關問題