4

In my .aspx page I have;

    <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" AspCompat="True" %>

    <%@ Register src="Modules/Content.ascx" tagname="Content" tagprefix="uc1" %>

    <!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:PlaceHolder ID="Modulecontainer" runat="server"></asp:PlaceHolder>
        </div>
        </form>
    </body>  
</html>

In my aspx.vb I have;

    Try
        Dim loadmodule As UserControl
        loadmodule = Me.LoadControl("~/modules/content.ascx")
        Modulecontainer.Controls.Add(loadmodule)
    Catch ex As Exception
        Response.Write(ex.ToString & "<br />")
    End Try

The result is an empty placeholder and no errors.

Thanks a lot for any assistance

P.S after Fat_Tony's answer I changed the code to;

Try
            Dim loadmodule As ASP.ContentModule
            loadmodule = CType(LoadControl("~\Modules\Content.ascx"), ASP.ContentModule)
            Modulecontainer.Controls.Add(loadmodule)
        Catch ex As Exception
            Response.Write(ex.ToString & "<br />")
        End Try

But still no results unfortunately.

4

2 回答 2

5

与其将您的 UserControl 声明为“Control”类型,不如将其声明为您在 UserControl.ascx 文件中指定的类名:

<%@ Control className="MyUserControl" %>

因此,在 .aspx 页面上的代码隐藏中:

Dim objControl as ASP.MyUserControl = CType(LoadControl("~\Controls\MyUserControl.ascx"), ASP.MyUserControl)

更多信息可在MSDN上找到。

编辑:检查用户控件的代码隐藏文件,并记下其中的命名空间和类名。当我创建我的用户控件时,它会自动添加到包含文件夹名称以及应用程序名称空间的名称空间中。

然后,在您的 .aspx.vb 中,将 .ascx.vb 文件中的“ASP.ContentModule”替换为“Namespace.ClassName”。此外,请确保您仍在调用占位符上的 Add 方法。

我的示例使用 C#,但如果您需要,我可以使用 vb。我的应用程序被方便地命名为“Tester”。

ASCX 代码隐藏:

namespace Tester.modules
{
    public partial class content : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}

ASPX 代码隐藏:

namespace Tester
{
    public partial class _Default : System.Web.UI.Page
    {   
        private Namespace.ClassName loadmodule;
        protected void Page_Load(object sender, EventArgs e)
        {
            loadmodule = (Namespace.ClassName)LoadControl("~/modules/content.ascx");
            Modulecontainer.Controls.Add(loadmodule);
        }
    }
}
于 2010-04-15T10:05:57.530 回答
2

我不太了解VB,但是您不需要将控件声明为UserControl而不仅仅是Control吗?例如尝试改变

Dim loadmodule As Control

Dim loadmodule As UserControl
于 2010-04-15T10:04:11.623 回答