user2974961
user2974961

Reputation: 365

Acess a control of a user control in a content page of a master page

I have user control (ascx) in a Master Page. Then I have a content page (aspx) that uses that Master Page. Now, in the content page, I want to access a hiddenfield control that is placed in the user control. How do I do that?

I tried the following but it returns null.

  Master.FindControl("MyHiddenField")
  Master.FindControl("MyUserControl1_MyHiddenField")

Thanks

Upvotes: 0

Views: 80

Answers (1)

mason
mason

Reputation: 32728

In your content page (.aspx) place this code. It will make the Master Page strongly typed for the content page.

<%-- The Page directive goes here --%>
<%@ MasterType TypeName="MyMasterClassName" %>
<%-- Rest of your code below.. --%>

In the Master Page code behind, place this code

public UserControlTypeName MyUserControl1
{
get {return myUserControl1; }
set {}
}

This makes the User Control instance public. You'll need to rename the ID of the user control to myUserControl1.

Then in your UserControlTypeName (or whatever the name of your class is for your User Control) you can make the inner controls accessible in the same manner we did on the master page.

public HiddenField
{
get {return myHiddenField;}
set {}
}

Obviously, rename the ID for MyHiddenField to myHiddenField to avoid a conflict.

Finally, this allows your content to access the controls within the user control that are on the master page through strong typing.

public void Page_Load(object sender, EventArgs e)
{
Master.MyUserControl1.MyHiddenField.Value="Hello, world!";
}

For further reference, see Working with ASP.NET Master Pages programmatically on MSDN.

If Microsoft Is Listening...

If for some reason a Microsoft ASP.NET developer is reading this answer, please consider doing something like this:

<asp:Button runat="server" scope="public" id="MyButton1 />

That would make it much easier than having to create wrapper properties to make inner controls publicly accessible.

Upvotes: 1

Related Questions