Access child user control's property in parent

2019-02-19 18:10发布

问题:

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 :(

回答1:

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";


回答2:

Using

Name_of_your_child_control1.PublicPropertyName

must work for your parent user control.



回答3:

Check the path and file names you are using, Anish. You have something wrong. Is Visual Studio telling you it can't find the control? Is it failing at compile time? Runtime?



回答4:

It's funny but whenever you add a property to a user control.

You need to register it again in the parent. So in your case,

Add a space at the end of this line and remove it again: $<% Register src="~/MyControl.ascx" tagname="MyControl" tagprefix="uc1" %>

This will re - register the user control and you will be able to access new properties.