Access Page control from User control

| October 23, 2010 | 0 Comments

Many times during programming we need to access .aspx page’s control from our user control. This article just tries to satiate query about how to access page control from user control in Asp.Net.

Scenario

Suppose you are having user control User.ascx and this user control contains single button with ID btnShow. And you are having a single .aspx page containing web control panel with ID pnlDesk.  You want to access panel control from user control’s button.

Solution

Register your user control on .aspx page, see Nested User Controls. We are going to use the user control’s Parent property. This property lets us to get reference to the server control’s parent control in the page control hierarchy. See code snippet(User.ascx.cs):

protected void btnShow_Click(object sender, EventArgs e)
    {
        Panel panel = (Panel)this.Parent.FindControl("pnlDesk");
        if (panel != null)
        {
            panel.Visible = true;
            panel.BackColor = System.Drawing.Color.Green;
        }
    }

Category: Asp.Net

Leave a Reply

%d bloggers like this: