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();
}
}
}
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:
App_code
create an abstract class (MyBasePage
for example) which inherits from Page
class and add abstract property (TestID
in your example),MyBasePage
and implement the property,.ascx.cs
cast this.Page
as MyBasePage
and use the property you want.