Access child user control's property in parent user control

13,051

Say your usercontrol was this:

<%@ Control Inherits="Project.MyControl" Codebehind="MyControl.ascx.cs" %>
<asp:TextBox ID="TB" runat="server" />

Your control code-behind:

namespace Project 
{
  public partial class MyControl : UserControl
  {
    public string MyTextProperty
    {
      get { return TB.Text; }
      set { TB.Text = value; }
    }
  }
}

In your parent page that included the control, like this:

<%@ Register src="~/MyControl.ascx" tagname="MyControl" tagprefix="uc1" %>
<uc1:MyControl ID="MyControlID" runat="server" />

You can use that property in code:

MyControlID.MyTextProperty = "bob";
Share:
13,051
Anish Mohan
Author by

Anish Mohan

Updated on June 05, 2022

Comments

  • Anish Mohan
    Anish Mohan almost 2 years

    I have included a user control in another statically following code :


    place the folowing directive in the asp code of the parent page or usercontrol:

    <%@ Register src="Name_of_your_child_control.ascx" tagname="Name_of_your_child_control" tagprefix="uc1" %>

    use the following tag in the asp-code of the parent page/control:

    <uc1:Name_of_your_child_control ID="Name_of_your_child_control1" runat="server" />

    ..... But the issue is...i am not able to access the public properties of user control which got included(child user control) in given user control(parent user control)...

    Please help :(

  • Anish Mohan
    Anish Mohan about 14 years
    But ...for me it is coming as i can not access the property :(
  • Nick Craver
    Nick Craver about 14 years
    @Anish - If you reference it as if it were there and compile, what error do you get?
  • Anish Mohan
    Anish Mohan about 14 years
    Is ur parent page is also a user control ? Parent Page { uc1 { uc2 { } } }
  • Nick Craver
    Nick Craver about 14 years
    @Anish - You want to access the property from the Parent control's code-behind, or from the page's codebehind that contains the parent?
  • Anish Mohan
    Anish Mohan about 14 years
    I have 2 user controls : uc1 and uc2 Also a parent page p1. I have included uc1 inside p1. Now i need to include uc2 inside uc1...and access uc2 property inside uc1
  • Nick Craver
    Nick Craver about 14 years
    @Anish - If you follow my answer, just including the control in a UserControl instead of a page it should work just the same, you should be able to use MyControlID.MyTextProperty in the code-behind of the parent user control, what compile error do you get if you try?