Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.

Sponsors

News

Blog Directory
Blogging Fusion Blog Directory
Web Directory
Blog Directory
EatonWeb Blog Directory
GeekySpeaky: Submit Your Site!
Blog Directory
blogarama - the blog directory
Bloglisting.net - The internets fastest growing blog directory
Blogio.net blog directory
Free Blog Directory
blog search directory
Software Blogs
RSSMicro FeedRank Results
On our way to 1,000,000 rss feeds - millionrss.com
Listed in LS Blogs the Blog Directory and Blog Search Engine
blog directory
Link With Us - Web Directory
Web Blogs Directory Add Your Blog.com

Certificates

Links

Social

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.

Comments

Nick said:

I have a custom control base class that overrides page with the casted page, which makes this super easy to use.

# May 21, 2008 5:42 PM

Christopher Steen said:

ASP.NET A New Tutorial Series on Master Pages [Via: Scott Mitchell ] Using parent page properties in...

# May 22, 2008 1:08 AM

Christopher Steen said:

Link Listing - May 21, 2008

# May 22, 2008 1:08 AM

DigiMortal said:

Well... IMHO it is not a good idea to have such a smart user controls that know about their parent pages. This is bad dependency because you cannot reuse these user controls on the other pages or other projects. I think this topic is also worth a blog entry.

# May 22, 2008 2:01 AM

xdpnuke said:

good,Control.Parent ,

# May 26, 2008 11:17 AM

AlkontAhmad said:

sorru but i triy it but it didnt work with me i dont know why

# May 27, 2008 6:02 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)