Using parent page properties in user control
There may be situations when we need to use parent page properties from user control. I know, this situations is a warning sign - there's something wrong with UI structure if user controls should know their parents. So, how to get correct reference to parent page so we can use also custom properties defined there?
Let's suppose we have property called MyId in parent page of our user control and we want to call this property from user control.
If we use this code in our user control
protected void MyMethod()
Page myParent = this.Page;
// here we need to call MyID property
we will get just a Page - the base class for all Pages. This is because reference of Page is kept in base class of user controls. Whenever you create a user control it gets also the Page property. But every page we create is custom page that inherits the Page class and we may define our own custom properties.
If we have page called MyPage and it has property MyID then how can we refer to this ID? Solution is simple: we have to use casting.
After casting parent page to correct type we are able to use it's properties.