1

我有一个用户控件,它以编程方式多次包含第二个用户控件,但最终结果是根本没有为控件生成任何 HTML。

默认.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>

十.ascx

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

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

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

一.ascx

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

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

一.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)
4

1 回答 1

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

您可能必须在加载控件后删除构造函数并设置属性。

于 2012-07-10T04:12:27.940 回答