简体   繁体   中英

Accessing object in parent user control from 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-behind I'd like to access the value of the hidden field hfId in the click event of that button

I can't use a user control attribute and set it on Page_Load because the value of that hidden field is changing through jQuery events in the Parent.ascx control

Use the below code to access the hidden field from the child control. this.Parent will give the parent control & use FindControl to find the control by ID.

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

If you change the value of the hidden field on page load, then on button click, the updated value gets reflected.

您可以使用以下方式访问孩子的控件:

var hfId = (HiddenField)NamingContainer.FindControl("hfId");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM