简体   繁体   中英

Why are my dynamically added user controls showing having their ascx controls as null?

I created a new Control TestControl . On the front-end I gave it

<asp:Label ID="lblTest" runat="server" />

On the backend:

public partial class TestControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        lblTest.Text = "blah";
    }
}

When I load the control via:

        var control1 = LoadControl(typeof(TestControl), null);
        Controls.Add(control1);

I get an exception that lblTest is null.

Why is this occurring?

Use the relative path overload of the LoadControl method instead, as noted here.

http://msdn.microsoft.com/en-us/library/ewtd66a0.aspx

Edit: changed answer after research.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM