views:

36

answers:

3

Hi

I have a page which holds a custom webcontrol and a usercontrol. I need to reference of webcontrol in usercontrol class. So, I make the declaration of webcontrol as public in page class. But, when I do “this.Page.”, I don’t see the webcontrol listed in list provided by intellisense. Most probably, I am missing something.

In an asp.net page, how to get a reference of a custom webcontrol from a usercontrol?

Please advise. Thanks Pankaj

+1  A: 

If you know the ID of the webcontrol, you can just do:

Control ctrl = Page.FindControl (ID_of_the_webcontrol);
Gonzalo
A: 

Try to get control at the page with FindControl method :

Control yourUserControl = this.Page.FindControl("yourControlsID");

The Page class is the instance of your page, it's an instance of the base class System.Web.UI.Page. So you can't get the public property with Page unless you cast it to your page class' type.

Canavar
+2  A: 

You're probably better of making a method on the UserControl which accept an argument of your WebControl.

Then let the Page wire them up together.

Having a Usercontrol relying on Page.FindControl seems very much like a hack to me.

E.g. Something like this in your UserControl:

public void SetWebControl(MyWebControl control)
{
// Do whatever
}

And in your Page you'd do this:

override OnInit()
{
this.MyUserControl1.SetWebControl(MyWebControl1);
}

It's all pseudo code ofc :-)

Steffen
+1 totally agree
Claudio Redi