开发者

NullReferenceException when user control references usercontrol in parent user control

I have a user control (uc1) which inherits from uc2. uc2 has a user control (uc3) declared in the markup. I am trying to access uc3 from uc1 but I get NullReferenceException. I thought due to inheritance uc3 would instantiate but looks like I am missi开发者_如何转开发ng a step.

Clarification:

How does the child user control inherit the markup from the base class? The server controls in the base user control are null in the code behind of the base user control. Why?


Look at using the FindControl method and traverse the page structure. Rick Strahl's article: ASP.NET 2.0 MasterPages and FindControl() goes through this. This can be an expensive operation especially if you need to walk up and down the tree.

There is also a key difference between .Net 1.1 and 2.0 where in 1.1 the code behind inherits from the aspx page and you declare your control variable in both but 2.0 uses partial classes that combine to form a single class and only require a single declaration, see; http://msdn.microsoft.com/en-us/library/ms227671.aspx


have you tried uc1.uc3 = new uc3 where you create an instance of uc1? That should solve the problem.


public class Uc2: UserControl
{ private Uc3 _uc3; public Uc3 Uc3 { get { return _uc3; } } }

public class Uc3 : UserControl { } public class Uc1 : Uc2 { public Uc1() { Uc3 uc3 = this.Uc3; //or Uc3 uc3_interface = ((IUc3)Page).Uc3; } } public interface IUc3 { Uc3 Uc3 { get; } } public class PageContainer : Page, IUc3 { private Uc2 _uc2; //must be assigned or must exist in markup thus designer

    public Uc3 Uc3
    {
        get { return _uc2.Uc3; }
    }
}


Find control can do the job, but it's not a good practice. If you ever change the control id in the markup the compiler won't catch it, avoid at any cost using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls;

namespace WebApplication5 {

public class Uc2: UserControl  
{
    private Uc3 _uc3;

    public Uc3 Uc3
    {
        get { return _uc3; }
    }
}
public class Uc3 : UserControl
{
}
public class Uc1 : Uc2
{
    public Uc1()
    {
        Uc3 uc3 = this.Uc3;
        //or
        Uc3 uc3_interface = ((IUc3)Page).Uc3;
    }
}
public interface IUc3
{
    Uc3 Uc3 { get; }
}
public class PageContainer : Page, IUc3
{
    private Uc2 _uc2; //must be assigned or must exist in markup thus designer

    public Uc3 Uc3
    {
        get { return _uc2.Uc3; }
    }
}

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜