views:

57

answers:

3

How to get the parent page values from the usercontrol. I have a usercontrol in a page. On click of the usercontrols button i wanna get some values from the page after executing a method. i need those values in my usercontrol. What is the best way to get the results of the page in the usercontrol.

A: 

The Page property? http://msdn.microsoft.com/en-us/library/system.web.ui.control.page.aspx

codeape
Finally i got a solution for this. I am using delegate.Now i am able to get the value form my parent page after doing some operations.
Nimesh
+1  A: 

Raw way: First access Page property:

http://msdn.microsoft.com/en-us/library/system.web.ui.control.page.aspx

Next You can cast Page property to Your page type (whatever it is) or You can use Page.FindControl method to find Page values from other controls.

http://msdn.microsoft.com/en-us/library/31hxzsdw.aspx

In nice way, user control should expose event fired when this button has been clicked and page should subscribe to this event and return data to control.

Is this what You are looking for?

Rafal Ziolkowski
+1 for second approach. The way with the usercontrol firing an event is the best way, because no usercontrol should control a page. The page should catch that event and give the usercontrol necessary informations to show.Page is controller and usercontrol is only the view.Apart from that, when your usercontrol is used in different pages, casting to the page's special type will fail anyway.
Tim Schmelter
Yep, that's the whole point of using UserControl. Some people unfortunately prefer to take shortcuts...
Rafal Ziolkowski
+2  A: 

You can use the Page property to get a reference to the page object. However, the reference is not of the type of your specific page class, so you can't use it to access the specific members in the class without casting it first:

MySpecificPageClass page = (MySpecificPageClass)Page;

Now you can use the reference to access any public members of the class. Controls in the page are often declared as protected, so you might have to change their access level to public in order to access them from the outside.

Guffa
Casting will fail if usercontrol is on several pages(what usercontrols normally are used for). I prefer Rafaels second approach with the usercontrol firing an event for the page, then the necessary Informations are given from the page(which holds the reference) to the Usercontrol.
Tim Schmelter
@Tim: Good point. For user controls designed to be used on different pages the approach is of course completely different.
Guffa