Access to an object in a parent user control from a child user control

So, I have a user control, Parent.ascx:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Parent.ascx.cs" Inherits="Parent" %> <%@ Register TagPrefix="cc" TagName="Child" Src="~/Child.ascx" %> <asp:HiddenField ID="hfId" runat="server" /> <cc:Child ID="child1" runat="server" /> 

My child control Child.ascx contains a button, and in the code lock I want to access the value of the hidden field hfId in the click event of this button

I cannot use the user control attribute and set it to Page_Load because the value of this hidden field changes through jQuery events in the Parent.ascx control

+4
source share
2 answers

Use the code below to access a hidden field from a child control. this.Parent will provide the parent control and will use FindControl to find the control by identifier.

 HiddenField hfID = this.Parent.FindControl("hfId") as HiddenField; string hiddenvalue = hfID.Value; 

If you change the value of the hidden field when loading the page, then click the "OK" button, the updated value will be reflected.

+3
source

You can access the control from a child using:

 var hfId = (HiddenField)NamingContainer.FindControl("hfId"); 
+1
source

Source: https://habr.com/ru/post/1499204/


All Articles