views:

72

answers:

4

I don't know if this has to do with how FindControl works or how scope works. But my base class is having a hard time seeing the fields of child classes. Currently I'm planning have the derived class set a property in the base class, but there are a lot of derived classes, so that isn't a very attractive solution.

public class BasePage:Page
{
    public void DoSomethingWithDerivedPageControl()
    {
        //foo is always null.
        Control foo = FindControl("Foo");
    }
}

public class DerivedPage : BasePage
{
    //In real life, this is the code generated .aspx.designer.cs file.
    protected Label Foo;
}
+4  A: 

FindControl doesn't use fields - it uses the controls which have been added to the page, and checks their ids.

Presumably your control hasn't been added to the page at the time when DoSomethingWithDerivedPageControl is called.

It would be helpful if you could tell us what you're really trying to achieve... if all your derived types should have a control called Foo, why not just put it in the base class to start with?

Jon Skeet
Ah! You set me on the right track. It was in the control collection of of a Table control. I had to do a recursive search to find it. Couldn't move it to base class because it was a label embedded in a slightly different table on each page.
MatthewMartin
+2  A: 
public abstract class BasePage:Page 
{ 
    abstract protected Label Foo {get;}
    public void DoSomethingWithDerivedPageControl() 
    { 
        Control foo = this.Foo;
    } 
} 

public class DerivedPage : BasePage 
{ 
    override protected Label Foo { get; set;} 
} 

Now, I suspect that's not wholy fulfilling your need. But, a base class doesn't/cant' know about it's children. Your only option to find a random field in a child class, is to just ignore the fact that they are base/derived, and just use reflection of it, as if it were an unrelated class.

James Curran
@Miochael Meadows: Ya'know... as I was writing the abstract property, I said to myself, "I gotta remember to make the class abstract..."
James Curran
Elegant solution, too bad I don't have enough control over how visual studio code generates the .aspx.designer.cs files-- I wouldn't have a way to add the override to the declaration. (Or is there?)
MatthewMartin
+1  A: 

To answer your title question, inheritance runs from base class to derived class, not the other way. A member is either defined in a base class, and inherited by the derived class, or defined in the derived class and unknown to the base.

It stands to reason that a base class referring to a child member couldn't compile, since the base class definition has no knowledge of that member.

Buggieboy
A: 

Whoa, this is scary that your even trying to do this. The base class shouldn't know anything about the derived class.

Gary L Cox Jr