Loading custom controls programmatically into a placeholder (asp.net)

On 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 so much for any help

PS 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 there are no results yet.

+3
source share
2 answers

Instead of declaring your UserControl as a “Control” type, declare it as the class name specified in the UserControl.ascx file:

<%@ Control className="MyUserControl" %>

So, in the code on the .aspx page:

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

Additional information is available on MSDN .

EDIT: , . , , , .

.aspx.vb "ASP.ContentModule" "Namespace.ClassName" .ascx.vb. , , Add .

#, vb, . "".

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);
        }
    }
}
+4

VB, UserControl, Control?

Dim loadmodule As Control

Dim loadmodule As UserControl
+1

Source: https://habr.com/ru/post/1741249/


All Articles