Access child user control's property in parent user control

三世轮回 提交于 2019-12-01 10:38:10

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

Using

Name_of_your_child_control1.PublicPropertyName

must work for your parent user control.

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?

vikasjagtap96

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!