Search code examples
c#asp.netascx

web control access web form methods


My web form contains a web control and a asp:HiddenField. I am trying to access that hiddenfield in my asxc.cs file. I defined a public get,set block in my aspx.cs file. In web control, when I tried to call ReportPage.TestID, it does not recognize the Reportpage class. Is it the right way to access the HiddenField in the webcontrol? If so, how should I access the ReportPage class?

public partial class ReportPage : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    public int TestID
    {
        get
        {
            return Convert.ToInt32(TestIDHiddenField.Value);
        }
        set
        {
            TestIDHiddenField.Value = TestID.ToString();
        }
    }
}

Solution

  • You cannot directly access page controls from a user control because of Web Site compilation model. In short, ASP.NET compiles first App_code (its classes are visible from all the site) then user controls (.ascx) and when .aspx pages which use that controls.

    A workaround looks like this:

    1. In App_code create an abstract class (MyBasePage for example) which inherits from Page class and add abstract property (TestID in your example),
    2. Create a page which inherits from MyBasePage and implement the property,
    3. In .ascx.cs cast this.Page as MyBasePage and use the property you want.